How to return a single object instead of a collection in Laravel

10,298

Solution 1

While first() works for any kind of query, when you are fetching a model by id find() is the preferred method. Also you can combine the two with calls:

$facture = Facture::with('items', 'client')->find($id);

Solution 2

Here is the right code to get only a single object instead of a collection:

public function show($id)
{
    $facture = Facture::where('id', '=', $id)->with('items')->with('client')->first();
    return Response::json($facture);
}
Share:
10,298

Related videos on Youtube

Lucien Dubois
Author by

Lucien Dubois

Cofondateur de Dubois International Inc.

Updated on July 29, 2022

Comments

  • Lucien Dubois
    Lucien Dubois over 1 year

    I try to return a single object instead of a collection in Laravel. Actually this code works:

    public function show($id)
    {
        $facture = Facture::where('id', '=', $id)->with('items')->with('client')->get();
        return Response::json($facture[0]);
    }
    

    but I Would like to know if it's the right way to do it?

  • Lucien Dubois
    Lucien Dubois about 9 years
    Great, I like this compact way to do it! Is find($id) faster than first() ?
  • lukasgeiter
    lukasgeiter about 9 years
    find() actually does nothing else than adding a where condition for the primary key (where('id', '=', $id)) and then calling first(). But the syntax is nicer and you don't have to specify the name of the primary key everywhere :)
  • Jose Mhlanga
    Jose Mhlanga almost 4 years
    The first method also works fine and returns a single object instead of array!