Search code examples
phplaravellaravel-5.3laravel-blade

Undefined variable with custom made service provider


I was following a tutorial from Laracast to pass data to partials.[Note: Using Laravel 5.3] I have done every step as in the video, but I'm getting undefined variable error in partial (_nav).I did went through all comment in video and some of them also had same problem but there wasn't any solution. Don't know what went wrong.Is this because I'm using Laravel 5.3 and tutorial was made on Laravel 5

Below is my code: Added custom made service provider in config/app.php

App\Providers\ViewComposerServiceProvider::class,

Custom made service provider `ViewComposerServiceProvider.php

<?php
namespace App\Providers
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->composeNavigation();
    }
    public function register()
    {
    //
    }

    private function composeNavigation(){
        view()->composer('partials._nav','App\Http\Composers\NavigationComposer');
    }
}

NavigationComposer.php

<?php
namespace App\Http\Composers;
use Illuminate\Contracts\View\View;
use App\Tour;
class NavigationComposer{

public function compose( View $view)
   {
       $view->with('latest',Tour::latest()->first());
   }
}

Partials code (partials._nav)

<li><a href="#">{{$latest->title}}</a></li>

Solution

  • As you were aware that tutorial video was made on Larave 5 and you are doing it in 5.3. And method mentioned or say practiced in video doesn't work [not complete] in laravel 5.3. You are right about creating custom Service Provider and class to handel the query request.

    In your ViewComposerServiceProvider.php remove composeNavigation() mentod and add the following in boot() method

          View::composer(
            'partials/_nav', 'App\Http\Composers\NavigationComposer'
        );
    

    And other code seems all fine.Here is the official documentation