Home > database >  Undefined variable in laravel 9
Undefined variable in laravel 9

Time:11-07

I'm getting an undefined variable $title error. when I pass data from the controller to view I get this error.

Registration Form Controller

public function index ()
{
    $url = url('/register');
    $title = "Registration Form";
    $data = compact('title', 'url');
    return View('RegistrationForm')->with($data);
}

Route

Route::get('/register', [RegistrationFormController::class, 'index']);

View

<body>
<h1> {{$title}} </h1> 
<x-registration-form-component :country="$country" :url="$url" /> 

CodePudding user response:

You have to pass the $data variable as the second argument of the view() method:

public function index ()
{
    $url = url('/register');
    $title = "Registration Form";
    $data = compact('title', 'url');
    return view('RegistrationForm', $data);
}

CodePudding user response:

First, to answer your question:

When you use the compact method, you are placing those values in an array. You would need to call them like so:

{{ $data['title'] }}
{{ $data['url'] }}

However, you could clean the code up a little bit like this:

public function index()
{
  return view('RegistrationForm', [
    'url' => url('/register'),
    'title' => 'Registration Form',
  ]);
}

You can then use them in the blade file like so:

{{ $url }}
{{ $title }}
  • Related