Home > Back-end >  Get route with parameter not working Laravel 8
Get route with parameter not working Laravel 8

Time:03-04

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"  id="firstname" value=" {{ $key->firstname }}"> <br>
    <label>Last Name</label> <br>
    <input type="text" name="lastname"  id="lastname" value="{{ $key->lastname }}"> <br>
@endforeach

CodePudding user response:

In your controller function change this line.

$data = User ::all()-> where('id',$id );

To this

    $data = User ::where('id',$id )->get();

You can also check $userdata in your view before executing loop.

@if($userdata)
@foreach  ($userdata as $key)

       <label>First Name</label><br>
       <input type ="text" name = "firstname"   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
@endif

CodePudding user response:

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'));`

CodePudding user response:

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.

CodePudding user response:

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']);
  • Related