Home > database >  Undefined Variable in Laravel 8 view
Undefined Variable in Laravel 8 view

Time:12-11

I just want to Pass a Variable to the views about page.

This is the controller file

 public function about(){
    $name ="maneth";
    return view::make('about')->with('name', $name);
}

This is the about page

@switch($name)
@case(1)
    
    @break
@case(2)
    
    @break
@default
    
 @endswitch

This is the web file

Route::get('/about',function(){
return view('about',[PagesController::class, 'about']);
});

The Error is $name is undefined

I'm Using Laravel Framework 8.75.0

and PHP 7.3.33

CodePudding user response:

Your controller action is never being executed as your route definition is returning a view directly.

Change your route so that it calls your controller and action.

Route::get('/about', [AboutController::class, 'about']);

CodePudding user response:

As long as it doesn't require any real logic (database query etc.) you can do it with a closures in your route. Otherwise you have to call the controller from your route. This would look like this:

Route::get('/about', [AboutController::class, 'about' ])->name('about');

And this would be thee closures style:

Route::get('/about',function(){
   $name = 'Slim Shaddy';
   return view('about', ['name' => $name]);
});

CodePudding user response:

You are using callback in router's file and there you not sent the name variable,

You can bind controller and router file using :

Route::get('/about', [AboutController::class, 'about']);
  • Related