Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

laravel - can use eloquent model in blade view?

for example this is our simple blade view that called dashboard and our class model is "user" does it work to take use it inside blade like following code? line 1,12

{{use AppModelsUser;
$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>
question from:https://stackoverflow.com/questions/65904514/can-use-eloquent-model-in-blade-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are confusing things, you SHOULD pass variables to the view IN the controller and then use them in the view (as of your line 12th)

To use that variable in the view, you should pass it in the controller: i.e:

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
}

Then you can use {{$user->id}}

the "use AppModelsUser;" syntax should only be used on Controllers or PHP classes, if you indeed need to use the actual model in view (in a loop for example) you can achieve that also!

@foreach(AppModelsUser::all() as $user)
    <!-- html code -->
@endforeach

<!-- OR -->

{{ AppModelsUser::find(104)->name }}

Hope it helped!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...