0

I have the following controller where I try to select all the customers of a user (The ones with 'user_id' equal to the 'id' of the authenticated user). I know how to do it in the following way, but as you can see it is not very efficient since it selects more records than necessary.

public function index() // Http/Controllers/CustomerController.php:17
{
    $user_id = Auth::id(); // Get user ID

    $customers = Customer::all()->where('user_id', $user_id); // Select all users and then filter by ID

    return $this->showAll($customers, 200); // Return JSON response with response code
}

1 Answer 1

3

Change your $customers = Customer::all()->where('user_id', $user_id); to:

$customers = Customer::where('user_id', $user_id)->get();

https://laravel.com/docs/7.x/eloquent#retrieving-models

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, I forgot the get() when I tried it, I will accpt the answer when I can. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.