I’m starting to learn how to use Vue and Laravel. So I’m writting some Vue components to replace some parts of the blades.
In my application I have a Sugerencia
(suggest) model. Of course I have users
models and many others, but I need those two for this question
My SugerenciaController@index
is quite simple:
public function index() { $sugerencias = Sugerencia::orderBy('created_at', 'desc') ->with('user') ->paginate(10); return view('sugerencias.index', compact('sugerencias')); }
In my sugerencias/index.blade.php
I “send” the $sugerencia
to Vue with:
@foreach ($sugerencias as $sugerencia) ... <user-info :sugerencia="{{ $sugerencia }}"></user-info> ... @endforeach
And works as intended. user-info
is a Vue component that formats and displays the user’s info. In Vue, to access the user’s name, I use {{ sugerencia.user.name }}
in my template. So far, so good. But this works only in the collection.
Then I have my SugerenciaController@show
method, which is as simple as
public function show(Sugerencia $sugerencia) { return view('sugerencias.show', compact('sugerencia')); }
I assumed that in my sugerenciasshow.blade.php
I could use the same call for the user-info
Vue component as:
... <user-info :sugerencia="{{ $sugerencia}}"></user-info> ...
…but I can’t, since it’s not “sending” the user
relationship. I assume its because I’m not using the ->with('user')
as I did in the collection.
In the mounted()
method I placed a console.log(this.sugerencia)
and I get all sugerencia’s data, but not the user data (just the user_id
foreign key)
So question is, how do I “append” the user
relationship to the sugerencia
model, kinda like eager loading. I want to do something that as trivial as $sugerencia->user->name
in the ORM
Please forgive me if my English isn’t clear enough and feel free to edit
Advertisement
Answer
Honestly, I would decouple the logic here and load the page and vue component with a null value and then do ajax requests to get the required data. Or implement a standardized way of getting data from the controller to the vue components without having specific variables in my view
blade templates.
However, for your particular question, you could use Lazy eagar loading like this:
public function show(Sugerencia $sugerencia) { $sugerencia->load('user'); return view('sugerencias.show', compact('sugerencia')); }
From the docs:
Sometimes you may need to eager load a relationship after the parent model has already been retrieved. For example, this may be useful if you need to dynamically decide whether to load related models: