简体   繁体   中英

Undefined variable: categories (View: in Laravel) How to Solve This

Hy! i have problem in post page of blog using laravel 5.8. in home page its work fine this same form code for post page but i create error. idk why i have route for home page

Route::get('/' , 'IndexController@index');

and this is for post page

Route::get('/post/{app}' , [BlogController::Class, 'show']);

for the home page and all other pages the indexController is same like retrieving the categories i use the @include file for all the pages but when i use the different controller for the post page i create issue.

Blog Controller

public function show($id)
    {
        $post =Post::find($id)->where('status' , 'publish');
        return view('/post')->with('blogs' , $post);
    }

Index Controller

 public function index()
    {
        return view('welcome')
        ->with('post' , Post::all())
        ->with('images' , Image::all()->sortByDesc('publish_at')->take(1))
        ->with('categories' , Category::all())
        ->with('top_index' , Post::all()->where('status' , 'publish')->sortByDesc('publish_at')->take(2)->where('status' , 'publish'))
        ->with('recent_posts', Post::all()->take(8)->sortByDesc('publish_at')->splice(2)->where('status', 'publish'));
    }

this work fine but when i use the Blog controller in post page where the Index Controller is also use for Categories the error occur Help me Please

Error Undefined variable: categories (View: C:\\xampp\\htdocs\\cms\\resources\\views\\include\\header.blade.php) (View: C:\\xampp\\htdocs\\cms\\resources\\views\\include\\header.blade.php)

You have to pass variable in extend function and then use it in child blade as below,

@extends('header', ['categories' => $categories])

You cannot directly use variable of header in child component blades. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM