how to pass one data view and others view page in laravel

i have two pages file in my view
first is my home blade then second is category blade and both of them using extends asidenav
my problem is when im redirecting to category file it gives me a error Undefined variable: categories but in my home file when im redirecting it’s working fine . i will describe my code.

in my controller HomeController i pass one data categories to home.blade.php

class HomeController extends Controller
{
    public function home()
    {
        $categories = Category::select('id','name')->get();

        return view('home', compact('categories'));
     }

     public function category(){
        return view('category');
     }
}

the output of my home.blade.php

@extends('asidenav')
@section('section')
<main>
    this is homepage
</main>
@endsection

you can see in my home blade there is a extends asidenav . inside of my asidenav extends the data categories i passed is inside of that asidenav to make a list of categories

the output of my extends asidenav
where the data i pass categories

<ul>    
    @foreach($categories as $category)
        <li><a href="{{ route('category',$category->id) }}"><span>{{ $category->name }}</a>
    @endforeach
</ul>

when i click the ahref to redirect the category blade it gives the error undefined variable categories. but when im redirecting to home blade it’s working
the output of my category.blade.php

@extends('asidenav')
@section('section')
<main>
    this is category
</main>
@endsection

but when i tried this code in my category controller it’s working fine the error of undefined variable categories not showing

   public function category()
        {
          $categories = Category::select('id','name')->get();

             return view('category', compact('categories'));
        }

my point here is i want to pass only single data categories in my home blade and others file blade like a props but i don’t have a idea how to do that

>Solution :

You could create a service provider responsible for inyecting those variables without declaring them in your controller, in your boot method :

View::composer(['asidenav', 'home'], function($view){
    $categories = Category::all();

    return $view->with('categories', $categories);
})

Leave a Reply