Home > Blockchain >  How to get query of users in Laravel with where condition
How to get query of users in Laravel with where condition

Time:08-04

I have a table for users and in that table, I have the column user_type_id which is related to another table called user_types. There are specific roles(subscriber and admin). Now, In my controller, I want to get all users with the condition that their user_type_id is equal to 2. With this way of doing it, I am getting only the first row...

My Controller:

public function show($id)
{
    $subscriber = User::where('user_type_id', 2)->firstOrFail();
    return view('show_subscriber', compact('subscriber'));
}

CodePudding user response:

public function show($id) {
    $subscriber = User::where('user_type_id', 2)->get();
    return view('show_subscriber', compact('subscriber'));
}

CodePudding user response:

public function show($id) {
    $subscriber = User::where('user_type_id', 2)->firstOrFail();
    return view('show_subscriber', compact('subscriber'));
}

firstOrFail() will return the first matching record and if no matching record is found it will simply return 404- resource not found.

public function show($id) {
    $subscriber = User::where('user_type_id', 2)->get();
    return view('show_subscriber', compact('subscriber'));
}

get() will return all the matching records as a collection.

see details here https://laravel.com/docs/9.x/eloquent#not-found-exceptions.

https://laravel.com/docs/9.x/eloquent#collections

  • Related