skip to Main Content

I only need id data from a table for an insert data for another table. But I don’t know how?
So I created search data request

$iduser = User::where('username','like','%' . request('username') . '%')->get();

I can’t use $iduser->id or some similar caliber for getting id for that particular data because I get error despite there’s an id on database

property [id] does not exist on this collection instance

2

Answers


  1. You have a collection of Users. If you were to loop through them;

    foreach($iduser as $user){
    var_dump($user->id);
    }
    

    Or, if you pass the collection to the view, you can loop through it there and access it’s ID.

    Login or Signup to reply.
  2. The get() method will return an Eloquent Collection even you only have one result, you can use the first() method to get one object.

    So you should be able to get the id this way:

    $iduser = User::where('username','like','%' . request('username') . '%')->first()->id;
    

    Don’t hesitate to use dd() on your variable to see what is the type and the content of the variable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search