Extending a Navigation Menu in Partials in Laravel 5

This post is more of a reminder to myself on how to extend a menu in an included partial when using the PHP framework Laravel.

As of this writing I’m using Laravel 5.1.16.

Hopefully other people find it useful too.

Let’s say you have a similar folder setup to this in your project:

resources/views/
-- layouts
-- default.blade.php
-- partials
-- nav.blade.php
index.blade.php

The default.blade.php template includes the navigation partial:

<!DOCTYPE html>
<html lang="en">
<head>
    ...
</head>
<body>
    @include('partials/nav')

<div>
        @yield('content')
</div>
</body>
</html>

In order to be able to extend the navigation menu from within index.blade.php you need to add @yield(‘nav’) to the nav.blade.php file.

<ul>
<li><a href="{{ url('/') }}">Home</a></li>
@yield('nav')
</ul>

Then from within the index.blade.php file you can extend the navigation menu using the following code:

@extends('layouts/default')
@section('nav')
<li><a href="#">New Nav item</a></li>
@append {{-- @stop also works --}}

I’m not 100% sure this is the best way to do it, but I searched for a way to use @parent within the nav.blade.php file and could not find a solution.

Leave a comment if you know of a better way to achieve this.