Eloquent: find() and where() usage laravel

239,868

Solution 1

Your code looks fine, but there are a couple of things to be aware of:

Post::find($id); acts upon the primary key, if you have set your primary key in your model to something other than id by doing:

protected  $primaryKey = 'slug';

then find will search by that key instead.

Laravel also expects the id to be an integer, if you are using something other than an integer (such as a string) you need to set the incrementing property on your model to false:

public $incrementing = false;

Solution 2

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 = App\Flight::findOrFail(1);

$model = App\Flight::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/flights/{id}', function ($id) {
    return App\Flight::findOrFail($id);
});

Solution 3

To add to craig_h's comment above (I currently don't have enough rep to add this as a comment to his answer, sorry), if your primary key is not an integer, you'll also want to tell your model what data type it is, by setting keyType at the top of the model definition.

public $keyType = 'string'

Eloquent understands any of the types defined in the castAttribute() function, which as of Laravel 5.4 are: int, float, string, bool, object, array, collection, date and timestamp.

This will ensure that your primary key is correctly cast into the equivalent PHP data type.

Share:
239,868
Awa Melvine
Author by

Awa Melvine

Updated on July 08, 2022

Comments

  • Awa Melvine
    Awa Melvine almost 2 years

    I am trying to get a record from a posts database table using its id. I've been banging my head on the find() method for quite sometime now, confused as to why it wasn't working. Here is my query that looks correct to me but didn't work:

    $post = Post::find($id);
    $post->delete();
    

    Reluctantly i did this:

    $post = Post::where('id', $id);
    $post->delete();
    

    and surprisingly enough, it worked but I have no idea how.

    I also know that unlike find(), where() is a query builder and so I could also use it like this: Post::where('id', $id)->first()

    Any ideas about the difference in the way the methods work?

  • Ahmed Shefeer
    Ahmed Shefeer almost 6 years
    There are major differences in execution of the delete process though. If you are using the model instance to delete i.e. $post->delete(), two queries are run. One to retrieve the record from database using the find() method and second one to delete the record. When using query builder, only one query is executed, the model instance is never created. As a result any features on the Post model will not work. For example if you have a model delete event listener, it will not be executed.
  • Mathieu Bour
    Mathieu Bour almost 5 years
    Ahmed's anwser should be highlighted, since the difference can cause a lot of confusion.
  • Jovylle
    Jovylle over 2 years
    and can use this one. User::find($obj) which obj has the id as foreign key and named as user_id (table name plus "_id")