Undefined variable in laravel blade file

2.3k Views Asked by At

I am new to laravel kindly help me out to solve this error.

This is my controller function "edit"

public function edit($id)
{
    $user = User::find($id);
    return view('users.edit-profile',['user'=>$user]);
}

This is my view users.edit-profile

<div class=" mb-4" style="border: 1px solid #979797; border-radius: 4px;width: 360px;height: 40px;margin-left: 200px;" >
<input type="text" name="name" id="name" onkeyup="isEmpty()" value="{{$user->name}}" class="form-control" >
</div>

This is the route

Route::get('/edit_profile',[profileController::class,'index']);
Route::get('/edit_profile/{id}',[profileController::class,'edit'])->name('edit_profile');

This is the error

Undefined variable: user (View: C:\xampppp\htdocs\clipboard_nation\resources\views\users\edit-profile.blade.php)

this error display that the $user variable that I use in blade file is not defined.

4

There are 4 best solutions below

0
On

Try this

public function edit($id)
{
    $user = User::findOrFail($id);

    return view('users.edit-profile', compact('user'));
}
1
On

try this

public function edit($id) {
  $data['user']= User::findOrFail($id);
  return view('users.edit-profile', $data);
}
0
On

The error is being thrown in the blade file as $user does not exist.

An option would be to prevent that error occurring directly in the blade file, by giving a default value if the variable does not exist.

<input type="text" name="name" id="name" value="{{$user ? $user->name : ''}}" >
0
On

I had similar problem, try to add the user data to index method too

$user = User::find($id);
return view('users.edit-profile',['user'=>$user]);