Is it possible to assign a blade template to a model?
Instead of doing this:
@php $contact = Contact::find(1); @endphp
@include('contact', ['contact' => $contact])
I'd like to just do:
@php $contact = Contact::find(1); @endphp
{{ $contact }}
But latter obviously just spits out the model in json.
CodePudding user response:
It is possible with PHP's __toString()
magic method: https://www.php.net/manual/en/language.oop5.magic.php#object.tostring
Let's make an example for default User.php
model.
First, create a blade file for that model, lets create that as /resources/views/model/user.blade.php
and a dummy component;
<h1>{{ $user->name }}</h1>
<p>{{ $user->created_at->diffForHumans() }}</p>
Now make this default __toString()
for User
model.
Add this to app/Models/User.php
;
/**
* @return string
*/
public function __toString(): string
{
return view('model.user', ['user' => $this]);
}
Now you can test it directly in your routes/web.php
;
Route::get('test', function () {
echo \App\Models\User::first();
});
Or try to echo it in any view as;
{!! $user !!}
You can't use {{ $user }}
because you need that HTML tags, so you have to use it as {!! $user !!}