I am trying to create my first project in Laravel. I have tables urls and reviews, every url has many reviews. In index view I would like to list all urls with their latest 2 reviews.
model Url
public function reviews()
{
return $this->hasMany('App\Review');
}
model Review
public function url()
{
return $this->belongsTo('App\Url');
}
class UrlController
class UrlController extends Controller
{
public function index()
{
// here I would need to get all urls with latest two reviews for each url
$urls = URL::all();
return view('urls.index')->with('urls', $urls);
}
}
view Index
@foreach ($urls as $url)
<li>
// Echo url name
// Here I need to list 2 reviews
// Something like...
@foreach ($url->reviews as $review)
$review->text
@endforeach
</li>
@endforeach
Do I have code generally set correctly?
1.try - this code in UrlController applies to urls, not its reviews.
$urls = URL::with('reviews')->orderBy('created_at')->take(2)->get();
2.try This code will limit number of all fetched reviews, in this case only first url will receive review, while others will have zero.
$urls = URL::with([
'reviews' => function($q){
$q->orderBy('created_at', 'asc');
$q->limit(2);
}
])->get();
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire