Home > Blockchain >  Undefined variable in laravel blade file
Undefined variable in laravel blade file

Time:06-07

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  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}}"  >
</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.

CodePudding user response:

Try this

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

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

CodePudding user response:

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 : ''}}" >

CodePudding user response:

try this

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