从控制器输出数组以在 laravel 5 中查看的最佳方式

Best way to output array from controller to view in laravel 5

我目前认为可以从来自我的控制器的数组中输出数据:

<!DOCTYPE html>
<html>
  @foreach ($details as $detail)
  <head>
    <meta charset="utf-8">
    <title>{{ $detail->name }}</title>
  </head>
  <body>
    <h1>in view</h1>

      {{ $detail->name }}
      <br>
      {{ $detail->street }}
      <br>
      {{ $detail->city }}, {{ $detail->state }}. {{ $detail->zip }}


  </body>
    @endforeach
</html>

这是我控制器中的功能:

  $details = DB::table('restaurants')->where('id', $restaurant_id)->get();
  return view ('restaurant.detail')->with('details', $details);

我的问题是:有更好的方法吗?我尝试使用不带 @foreach 的 blade 语法,但没有成功。

我不想多次输出这个,我有 foreach 的唯一原因是因为这是我可以让它输出的唯一方法。

如果这是它应该的工作方式,不用担心,我对 blade 还不够熟悉,不知道是否有更好的输出方式。

谢谢!

为什么要在页面中使用多个 title 标签?没有任何意义。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title><!-- What do you want to show here ? --></title>
  </head>
  <body>
    <h1>in view</h1>
        @foreach ($details as $detail)
            {{ $detail->name }}
            <br>
            {{ $detail->street }}
            <br>
            {{ $detail->city }}, {{ $detail->state }}. {{ $detail->zip}}
        @endforeach
  </body>
</html>  

您似乎是通过 ID 选择内容,所以这可能是独一无二的。默认情况下,当您执行 ->get() 时,它会 return 一组结果,因为它假设总是有超过 1 个的机会。当按 ID 选择时,您知道该 ID 是否存在某些东西,只有将成为其中之一。您可以将代码更改为:

$detail = DB::table('restaurants')->where('id', $restaurant_id)->first();
return view ('restaurant.detail')->with('detail', $detail); 

<html>
  <head>
    <meta charset="utf-8">
    <title>{{ $detail->name }}</title>
  </head>
  <body>
    <h1>in view</h1>

      {{ $detail->name }}
      <br>
      {{ $detail->street }}
      <br>
      {{ $detail->city }}, {{ $detail->state }}. {{ $detail->zip }}


  </body>
</html>

我强烈建议您查看 Eloquent

eloquent 模型示例:

class Restaurant extends Model {} //The table name for model "Restaurant" is assumed to be restaurants

那么您可以找到一家餐厅:

$detail = Restaurant::find($restaurant_id);

您可以通过以下方法实现,

1. 使用 first() 检索单个记录,如下所示,

// Controller Code
$detail = DB::table('restaurants')->where('id', $restaurant_id)->first();

<!-- View Code -->
<title>{{ $detail->name }}</title>

2。使用 find() 通过其主键检索单个记录,如下所示。它的工作原理与 first() 类似,但它通过主键检索数据。

// Controller Code
$detail = DB::table('restaurants')->find($restaurant_id);

<!-- View Code -->
<title>{{ $detail->name }}</title>

3。您可以像在问题中那样使用 get() 但您需要将其作为索引为 0 的数组进行访问。我假设您的查询只会检索一条记录。即使它检索多条记录也不会失败,但您只会首先在您的视图中记录。

// Controller Code
$details = DB::table('restaurants')->where('id', $restaurant_id)->get();

<!-- View Code -->
<title>{{ $detail[0]->name }}</title>

可能还有更多方法,但到目前为止我只使用了这些方法。