Laravel Eloquent Query Retrieving Single Models


Image title

Once you have created a Eloquent model and its associated database table, you can start retrieving data from your database. Think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model. Of course, in addition to retrieving all of the records for a given table, you may also retrieve single records using find or first. Instead of returning a collection of models, these methods return a single model instance:

<?php

use App\Product;

// Retrieve a model by its primary key...
$product = Product::find(1);

// Retrieve the first model matching the query constraints...
$product = Product::where('active', 1)->first();

You may also call the find method with an array of primary keys, which will return a collection of the matching records:

<?php

use App\Product;

// Retrieve models by array of primary keys...
$products = Product::find([1, 2, 3]);


Not Found Exceptions

Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:

$model = Product::findOrFail(1);

$model = Product::where('legs', '>', 100)->firstOrFail();

If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:

Route::get('/api/products/{id}', function ($id) {
    return Product::findOrFail($id);
});


If you have any other questions, experience or insights on "Laravel Eloquent Query Retrieving Single Models" please feel free to leave your thoughts in the comments bellow which might be helpful to someone!

Written by Akram Wahid 6 years ago

are you looking for a chief cook who can well craft laravel and vuejs, to make some awsome butterscotch,
yes then it is right time for you to look at my profile.

Do you want to write Response or Comment?

You must be a member of techalyst to proceed!

Continue with your Email ? Sign up / log in

Responses

Be the first one to write a response :(

{{ item.member.name }} - {{ item.created_at_human_readable }}

{{ reply.member.name }} - {{ reply.created_at_human_readable }}