Hi everybody. I'm new to Laravel and this is the first framework I use, I'm loving it so far. I have a question about how to pass data to a view from multiple tables.
I'm working in a fashion application who has an outfit model. The outfit can belong to one or more brands, one or more fashion styles, and one or more stores. I defined the relationships using Laravel, and I came up to the following model:
Outfit Model:
protected $table = 'outfits';
[...]
public function brands(){
return $this->belongsToMany('Brand','outfit_brands','outfit_id','brand_id');
}
public function styles(){
return $this->belongsToMany('Style','outfit_styles','outfit_id','style_id');
}
public function stores(){
return $this->belongsToMany('Store','outfit_stores','outfit_id','store_id');
}
[...]
Now I can go to my Outfit controller and to pass data into the view like this :
$outfits = Outfit::all();
foreach($outfits as $item){
$id = $item->id;
$item->mybrands = Outfit::find($id)->brands->lists('name');
$item->mystyles = Outfit::find($id)->styles->lists('name');
$item->mystores = Outfit::find($id)->stores->lists('name');
}
return View::make('outfits.index', compact('outfits'));
In the view, I get all the data by doing this :
[...]
@foreach ($outfits as $item)
[...]
<td>{{ $item->name }}</td>
<td>{{ $item->description }}</td>
[...]
<td>{{ HTML::ul($item->mybrands, array('class'=>'list-unstyled')); }}</td>
<td>{{ HTML::ul($item->mystyles, array('class'=>'list-unstyled')); }}</td>
<td>{{ HTML::ul($item->mystores, array('class'=>'list-unstyled')); }}</td>
[...]
@endforeach
This works perfectly, but I'm completely sure this is not the legal, neither the optimal way to pass data to a view, and that the most experienced fellows around here are facepalming themselves in disbelief. I would like to do the things well from the start, so I'm here to check with you guys about what is the right way to achieve the same result properly.
PS: I was reading the documentation about view composers, that seems to be a fair alternative, but it was quite complex for my level of knowledge and it assume a lot of things that I don't know how to do yet.
Thank you in advance for your help!
Looks good to me.
Only this:
$item->mybrands = Outfit::find($id)->brands->lists('name');
$item->mystyles = Outfit::find($id)->styles->lists('name');
$item->mystores = Outfit::find($id)->stores->lists('name');
You should store Outfit::find($id) in a variable. If you want, you can also use "with".
Greetings.
Thank you @Ruk33 for your answer. I thought Laravel itself had some special method to deal with this. I'm happy I found the right solution from the start.
Great question, elaborated very well! I also find myself often in the situation where I'm not sure how to pass data to the view. Further opinions are appreciated!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community