【问题标题】:can use eloquent model in blade view?可以在刀片视图中使用 eloquent 模型吗?
【发布时间】:2021-04-30 10:10:29
【问题描述】:

例如,这是我们称为仪表板的简单刀片视图,我们的类模型是“用户” 像下面的代码一样在刀片内部使用它是否有效?第 1,12 行

{{use App\Models\User;
$user= User::where('id', '1234')->first();}}
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot>
<div class="py-12">
    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
            <div class="p-6 bg-white border-b border-gray-200">
                {{ $user->name }}
            </div>
        </div>
    </div>
</div>

【问题讨论】:

  • use 是一个 PHP 指令(这是正确的词吗?)所以需要被包裹在一个 &lt;?php use App\Models\User; ?&gt; 块(或等效的 @php ... @endphp 刀片块)中但是你实际上并不在这里使用User 作为一个类。只有$user作为变量

标签: laravel eloquent view model laravel-blade


【解决方案1】:

你把事情弄糊涂了,你应该将变量传递给控制器​​中的视图,然后在视图中使用它们(从你的第 12 行开始)

要在视图中使用该变量,您应该在控制器中传递它:即:

publix function index(){
   $user = User::find(1);
   return view('index',['user'=>$user]); //'user' is the name of the variable in the view and $user the value that variable will take
}

那么你可以使用{{$user-&gt;id}}

“使用 App\Models\User;”语法只能用于控制器或 PHP 类,如果您确实需要在视图中使用实际模型(例如在循环中),您也可以实现!

@foreach(App\Models\User::all() as $user)
    <!-- html code -->
@endforeach

<!-- OR -->

{{ App\Models\User::find(104)->name }}

希望对您有所帮助!

【讨论】:

    【解决方案2】:

    您可以像在任何其他 .php 文件中一样导入 .blade.php 文件中的类:

    @php
    use App\Models\User;
    $user= User::where('id', '1234')->first();
    @endphp
    <x-app-layout>
    <x-slot name="header">
    <h2 class="font-semibold text-xl text-gray-800 leading-tight">
    {{ __('Dashboard') }}
    </h2>
    </x-slot>
    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    {{ $user->name }}
                </div>
            </div>
        </div>
    </div>
    
    

    在这种特殊情况下,这样做几乎没有什么好处,而且在视图代码中发生数据库查询通常不是一个好主意,因为视图不应该负责检索模型。这是控制器或从控制器调用的助手的责任。

    【讨论】:

      【解决方案3】:

      您应该在控制器和模型中定义所有逻辑。 并将变量中的数据传递给刀片文件。

      在那里你可以使用所有数据

      @foreach(....)
      
      @endforeach
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-03
        • 2018-07-07
        • 2015-05-14
        • 1970-01-01
        • 1970-01-01
        • 2015-10-09
        • 1970-01-01
        • 2016-06-25
        相关资源
        最近更新 更多