Removing Logic From Your Laravel Views Using View Partials

Blade Views

Committed to the LaraBrain by: wjgilmore (@wjgilmore) at October 19, 2015 3:11 pm

Learn how to dramatically reduce logic in your views using view partials

Each LaraBrain tip can be starred (favorited) by LaraBrain members in order to easily return to them in the future. A belongsToMany association relates tips to users, meaning you can determine whether a user has previously starred a tip using the contains() method:

$tip = Tip::find(55);

In order to visually denote whether a user has starred a tip, the LaraBrain code uses the contains method like so:

@if ($user->stars->contains($id))
    <i id="star" class="glyphicon glyphicon-star"></i><br />
    <i id="star" class="glyphicon glyphicon-star-empty"></i><br />

However, I'd rather not pollute the view with @if conditionals whenever possible, and so instead manage this code in a view partial. View partials are like mini views that can be inserted into other views. I manage my view partials in a directory named partials found in the resources/views directory, and prefix the view partial names with _, so this particular view partial is called _star_button.blade.php. I'll then pass the tip ID and user object into that view from the Tips controller's show.blade.php view:

  ['id' => $tip->id, 'user' => Auth::user()]