Search code examples
phplaravel-5

Laravel, need variable on admin routes


I need a variable for my admin dashboard, so my guess is to put something inside cache so I can do I can access it in my admin layout-template. I need to merge 2 config files with links:

$dashboard_links = \Auth::user()->hasRole(['root', 'admin'])
    ? config('dashboard')
    : config('dashboard-user');
$taxonomies = Config::get('taxonomies');

foreach ($taxonomies as $name => $config)
{
    $original_array = array_splice( $dashboard_links, $config['order'], 0 );
    $dashboard_links = array_merge ($original_array, [$name => $config], $dashboard_links); 
}

I want the $dashboard_links available in the base template "resources/views/layouts/master.blade.php". But I don't want to create the variable on each page request or put it in every controller. It's only needed when someone is logged as an administrator and visits any admin page. I am not that good in programming so I don't know what is the best approach. These are my routes if helpfull:

Route::group(['middleware' => ['role:admin']], function()
{
    // edit post form
    Route::get('post/edit/{slug}', [
        'as'    => 'post-edit',
        'uses'  => 'Post\AdminController@edit'
    ]);

        Route::get('medialibrary/edit/{id}', [
        'as'    => 'media-edit',
        'uses'  => 'MediaLibrary\MediaController@edit',
    ])->where('id', '[0-9]+');

    // and so on...
});

Solution

  • You should consider using a view composer https://laravel.com/docs/5.6/views#view-composers

    View composers allow you to pass variables to all views associated with the composer.

    So you would register a new service provider to associate your composer to specific routes. Then in your composer poplate the variable, and pass it to all admin views.