如何从 blade 中的 eloquent 过滤器中提取数据

How to pull out data from eloquent filter in blade

我需要能够在 for each 循环之外提取类别标题,但我不知道如何定义变量

当它已经定义时我可以从循环内部完成它但是我在我不想要的循环的每次迭代中都得到它。到目前为止我的代码是

@extends('layouts.games')

@section('content')

<h1>{{TITLE TO GO HERE}}</h1>
<div class="row saleGames">
  @foreach($allGames as $game)
  <div class="col-3"><img height="50" src="{{$game->image ? $game->image->file : 'http://placehold.it/400x400'}}" class="buytItems"></td><br>Price £10<br><br><button class="btn btn-success">Add to Basket</button></div>
  @endforeach
</div>
@endsection

我需要用数据库中的标题替换 TITLE TO GO HERE,但我不知道如何定义它以便在循环外使用

  public function show(Categories $category)
    {
      $allGames = Games::where('categories_id', $category->id)->get();      
      return view('games', compact('allGames'));
    }

将您的代码更改为以下代码:

public function show(Categories $category)
    {
      $allGames = Games::where('categories_id', $category->id)->get();
      $title = $catgeory->title // this will be name of the field you want to display in your view ;

      return view('games', compact('allGames', 'title'));
    }

然后在您的 blade 文件中:

@extends('layouts.games')

@section('content')

<h1>{{$title}}</h1>
<div class="row saleGames">
  @foreach($allGames as $game)
  <div class="col-3"><img height="50" src="{{$game->image ? $game->image->file : 'http://placehold.it/400x400'}}" class="buytItems"></td><br>Price £10<br><br><button class="btn btn-success">Add to Basket</button></div>
  @endforeach
</div>
@endsection

在紧凑数组中添加类别,

public function show(Categories $category)
{
  $allGames = Games::where('categories_id', $category->id)->get();      
  return view('games', compact('allGames','category));
}

然后在你的 blade

<h1>{{ $category->name}}</h1>