'Get route with parameter not working Laravel 8
I'm using Laravel 8, and when I use a GET route with parameter {id}, it shows "undefined variable" in view.
Error message
Undefined variable $userdata (View: D:\xampp\htdocs\ecommerce\resources\views\profile.blade.php)
Route
Route::get("/profile/{id}", [UserController ::class,'showUserdata']);
Controller
function showUserdata($id)
{
id = User::find($id);
$data = User::all()->where('id',$id;
return view ('profile', ['userdata' => $data]);
}
View
@foreach ($userdata as $key)
<label>First Name</label><br>
<input type="text" name="firstname" class="form-control" id="firstname" value=" {{ $key->firstname }}"> <br>
<label>Last Name</label> <br>
<input type="text" name="lastname" class="form-control" id="lastname" value="{{ $key->lastname }}"> <br>
@endforeach
Solution 1:[1]
There is an error in your query
$data = User ::all()-> where('id',$id );
to
$userdata = User::where('id',$id )->get();
And you are sending data to the blade in a wrong way
`return view ('profile',compact('userdata'));`
Solution 2:[2]
The error is in view usage, not in other parts of your code. View is seen in your code as a function not a Model with functions!
I use view in a different way like this:
View::make('profile',['userdata'=>$data])->render();
Please see the View::make where make is the function associated with the "model" View.
Solution 3:[3]
There is some misstakes in your code, don't worry you will ge the hang of it. I have compiled an alternative for you that might be what you want.
Your previous code
function showUserdata($id)
{
id = User::find($id);
$data = User::all()->where('id',$id;
return view ('profile', ['userdata' => $data]);
}
Change to this:
function showUserdata($id)
{
$data = User::find($id);
return view('profile', ['userdata' => $data]);
}
Another solution is to use route model binding.
use App\Models\User;
function showUserdata(User $User)
{
return view('profile', ['userdata' => $user]);
}
And your web.php would look like:
Route::get("/profile/{user}", [UserController::class,'showUserdata']);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Muhammad Shareyar |
| Solution 2 | Costel-Irinel Viziteu |
| Solution 3 | Adam |
