Reputation: 378
Im adding VueJs Components to my Laravel App and im struggling with this question:
I have 2 models, Concessions and Brands, with a ManyToMany relationship like this:
Concession Model
public function brands()
{
return $this->belongsToMany('App\Brand');
}
Brand Model
public function concessions()
{
return $this->belongsToMany('App\Concession');
}
in the controller im fetching the data from all the Concessions and returning to the view like this:
public function concessions()
{
$concessions = Concession::all();
return view('MyConcessionsView', compact('concessions'));
}
on my Laravel View i can access to $concessions[0]->brands
with no problem and everything is working fine.
So, im adding my Vue component, and i'm passing the prop $concessions to that component:
<concessions-map :con="{{ $concessions }}"></concessions-map>
On my Vue component im accepting the prop 'con' and i can display all the elements from that array. BUT i need access from each brand form each concession and when i try, for example, display con[0].brands[0]
or even con[0].brands
it gives me the error Cannot read property 'brands' of undefined".
I even pass this prop to State on Mounted() lifecycle method:
mounted() {
this.concessions = this.con;
}
and on Vue DevTools i have the array with 35 objects.. but i can access the property brands from each one.
Any advice?
Thanks (a lot) in advance!
Upvotes: 0
Views: 800
Reputation: 579
hi,
you can work with Axios is a better way so
-1 define a function in your concessions controller to get every concessions with its brands
public function getConcessions(){
$concessions= Concession::with('brands');
return $concessions;
}
-2 define a route to fetch this data in your web.php for example
Route::get('/concessions/getData','ConcessionController@getConcessions');
-3 fetch data with axios from your vuejs component
loadConcessions(){
axios.get("/concessions/getData")
.then(({data}) => {
this.concessions = data.data
});
and do not forget to add this function in your mounted methode
mounted() {
this.loadConcessions()
}
-4 now you can display the data fetched in your vuejs component
in your case you do for example
{{concessions.brands}}
and even you can read it as a loop with v-for for example read it in a table
<tr v-for="concession in concessions.data" :key="concessions.id">
<td class="text-center">{{concession.brands}}</td>
</tr>
so for each concession, it will display its brands
Upvotes: 0
Reputation: 127
$concessions = Concession::with('brands')
This is what you need.
when you execute
$concessions[0]->brands
You are making a new request to the database.
Upvotes: 1