Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sebastiansulinski's avatar

View Composer : bind composer to a partial

I'm trying to figure out whether it is possible to bind a composer to a partial.

I have a template partial navigation.blade.php which I then include within the main layout.blade.php file.

I've set up the binding

view()->composer(
    'admin.template.partials.navigation',
    'Cmd\Composers\Admin\MainNavigation'
);

and my MainNavigation class looks like this

class MainNavigation implements Contract {

    /**
     * @var Guard
     */
    private $guard;


    /**
     * @param Guard $guard
     */
    public function __construct(Guard $guard)
    {

        $this->guard = $guard;
    }

    /**
     * Bind user's first name to the view.
     *
     * @param View $view
     */
    public function compose(View $view)
    {

        $view->with('userName', $this->guard->user()->first_name);

    }

}

I then include the partial in my layout

@include('admin.template.partials.navigation')

and from within the partial blade view I simply call the variable $userName (within curly brackets), but when I run it I get

ErrorException in fc84a079a60140648eee92d4f9e5e88b line 20: Undefined variable: userName (View: /home/vagrant/Code/framework/resources/views/admin/template/partials/navigation.blade.php) (View: /home/vagrant/Code/framework/resources/views/admin/template/partials/navigation.blade.php) (View: /home/vagrant/Code/framework/resources/views/admin/template/partials/navigation.blade.php)

Any idea?

0 likes
5 replies
RayRutjes's avatar

Did you setup your binding in a service provider? If yes have you thought about adding your service provider to the config/app.php file?

sebastiansulinski's avatar

It's all done - service provider created and added to the providers array. Everything runs, but it doesn't seem to recognise the composer value I bounded to the view.

RayRutjes's avatar

Have you tried a dd() in your mainNavigation to see if it is actually parsed?

sebastiansulinski's avatar

Well - the error I'm getting is from within this file navigation.blade.php and using dd() doesn't really return anything new as this variable doesn't seem to reach this view. I'm wondering if composers are only ever executed when you actually call view on the view file.

sebastiansulinski's avatar
Level 3

I've found the problem - and it was related to some changes I've done earlier. It works fine now.

Please or to participate in this conversation.