2

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.

James Z
  • 12,209
  • 10
  • 24
  • 44
Timothy
  • 69
  • 7

4 Answers4

0

Try this

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

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

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 : ''}}" >
MaggsWeb
  • 3,018
  • 1
  • 13
  • 23
0

try this

public function edit($id) {
  $data['user']= User::findOrFail($id);
  return view('users.edit-profile', $data);
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jun 07 '22 at 19:24
0

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]);
Pepe F.
  • 9
  • 4