Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Value to header in every page Laravel

Tags:

php

laravel

I have a header in every page, the header has member id. I created header.blade.php , and included in default.blade.php , which is something like this:

default.blade.php

<header>
    @include('includes.header')
</header>

I need to pass member id from controller.php to header.blade.php , this is the problem. How to do it?

like image 220
hahahaha Avatar asked Sep 29 '22 02:09

hahahaha


1 Answers

I suggest using a view composer. This will allow you to define/assign a variable into any given template on any request. For the sake of demonstration, I'll assume your "member id" is 5. You'd need to create a service provider, I've copied this from the docs:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider {

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        // Using Closure based composers...
        View::composer('includes.header', function($view)
        {
            return $view->with('memberId', 5);
        });
    }

    /**
     * Register
     *
     * @return void
     */
    public function register()
    {
        //
    }

}

You will need to register this service provider in config/app.php. Once you have done this, the variable $memberId will be available in your header template. {{ $memberId }}

like image 74
Logan Bailey Avatar answered Oct 10 '22 09:10

Logan Bailey