【问题标题】:How to pull out data from eloquent filter in blade如何从刀片中的 eloquent 过滤器中提取数据
【发布时间】:2019-07-03 11:36:14
【问题描述】:

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

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

@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'));
    }

【问题讨论】:

  • 从哪里得到变量$allGames?我猜在控制器操作中,所以还要从数据库中获取标题并将其作为$title 发送到视图然后打印它......
  • 能否将$allGames变量的内容添加到问题中
  • 你能把渲染这个视图的控制器的方法贴出来吗?
  • 我添加了控制器方法
  • 你想从数据库和哪个表中显示哪个标题?

标签: laravel laravel-blade laravel-5.8


【解决方案1】:

在紧凑数组中添加类别,

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

然后在你的刀片中

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

【讨论】:

    【解决方案2】:

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

    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'));
        }
    

    然后在你的刀片文件中:

    @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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-30
      • 1970-01-01
      • 2019-09-03
      • 2021-07-07
      • 2018-08-08
      • 1970-01-01
      • 2021-04-03
      • 2018-05-19
      相关资源
      最近更新 更多