'Undefined variable problem on Laravel 9.x
I'm trying to get a my title variable from my control page and display it on the about page.
I don't think I have a typo, but it might me. I'm not sure.
Here is my control page code;
class PagesController extends Controller
{
public function index(){
$title = 'Welcome to Laravel';
return view ('pages.index')->with('title', $title);
}
public function about(){
$title = 'About us';
return view ('pages.about')->with('title', $title);
}
public function services(){
$title = 'The services';
return view ('pages.services')->with('title', $title);
}
}
In this page, the index and services functions work fine, but I can't get the about page.
Here is my display pages;
This is Index page
@extends('layouts.app')
@section('content')
<h1>{{$title}}</h1>
<p>This is the Laravel Application</p>
@endsection
This is the about page:
@extends('layouts.app')
@section('content')
<h1>{{$title}}</h1>
<p>This is the About page</p>
@endsection
Solution 1:[1]
Since this is a test application from a lesson, I forgot to delete some extra code in my route file.
This is my route file:
Route::get('/', 'App\Http\Controllers\PagesController@index');
Route::get('/about', 'App\Http\Controllers\PagesController@about');
Route::get('/services', 'App\Http\Controllers\PagesController@services');
The commented area shouldn't be here. That was the whole problem over here...
// Route::get('/about', function(){
// return view ('pages.about');
// });
Solution 2:[2]
Do this:
return view ('pages.index', compact('title'));
or:
return view ('pages.index', [
'title' => $title
]);
Solution 3:[3]
Since you are returning just the title, there isn't any need to call any verbs. Rather you should directly call the view:
route::view('/about', 'Pagecontroller@about');
or
pass the parameter by compact:
return view ('pages.index', compact('title'));
or
return view ('pages.index', ['title' => $title]);
Solution 4:[4]
This form of passing variables is a short-lived entry of a variable into the session. Then accessing the variable on the page should look like this:
{{ session('title') }}
If you want to pass data to the view, then you need to use the method
return view('pages.services', ['title' => $title]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
| Solution 2 | aquinoaldair |
| Solution 3 | Peter Mortensen |
| Solution 4 | Peter Mortensen |
