Home > Back-end >  Undefined Variable problem on Laravel 9.x
Undefined Variable problem on Laravel 9.x

Time:03-06

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 index and services functions works 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 about page

@extends('layouts.app')
@section('content')
<h1>{{$title}}</h1>
<p>This is the About page</p>
@endsection

The error I have

Please let me know if my question is not clear.

CodePudding user response:

Do this:

 return view ('pages.index', compact('title'));

or:

return view ('pages.index', [
   'title' => $title
]);

CodePudding user response:

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', ['titel' => $title]);

Laravel views

  • Related