$post = Post::findOrFail(1) Īs you can see above example using findOrFail() method will shorten your code if you need to abort the process if no record is found. If you want to abort the process like the above code then the below code will do the same. That's why findOrFail () method in Laravel. Usually, we use find () method for finding by model primary key but sometimes we need to use abort () function helper if the primary key value is not found. And the different usage of these methods. Laravel Eloquent findOrFail() basic example In this post, I will share on how to use find () and findOrFail () methods in Laravel Eloquent query. $post = Post::find(1) īut if we need to abort the process if not record found using find() then see the following code below: $post = Post::find(1) You can pass it an array, but that just makes it look for multiple rows. The below example will just display null if no record is found by the given ID. Model::find only works with single-column keys. That's why findOrFail() method in Laravel eloquent is useful for this kind of scenario. This will ensure that your primary key is correctly cast into the equivalent PHP data type. Usually, we use find() method for finding by model primary key but sometimes we need to use abort() function helper if the primary key value is not found. 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. In this post, I will share on how to use find() and findOrFail() methods in Laravel Eloquent query.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |