Very Useful Laravel Eloquent XorY methods

Laravel is one of the best PHP framework and without a say the documentation is gold. The popularity of the framework is increasing day by day. Laravel is a feature rich framework. Well, as i said the documentation is gold however some functions are hidden and some are well documented. Today we’re going to achieve some hidden and some well known Eloquent XorY methods in this series.

Eloquent XorY is not an actual terminology for the functions i guess. In a simple way, this means to do X else Y .

findOrFail

If you are working with laravel, this method should not be new to you but if it is then this method takes an id as an parameter and will returns a single model else if no matching model exists then will abort with 404 error.

Above code is equivalent to the code given below.

firstOrFail

Above codes will work alright ! But instead of writing extra codes and spaces, why not do all that in one line code right 🙂

firstOrCreate

In above code, we are first trying to find a user with a given phone number and if this returns null then creating a new user with the given phone. The code seems pretty alright but what if we do it with a more simple one line code 🙂

firstOrNew

Like firstOrCreate, this method will try to locate a record with the given attributes. However, if model does not exist then the new model instance will be returned and the returned instance is not persisted . We need to save it manually.

updateOrCreate

Just like above methods and as the name implies itself, we can guess this function will update or create the model with the given attributes.

Above code can be written neatly as below code 🙂

If there is a user whose email is info@laravel-nepal.com and name is laravel-nepal , set the admin column to 1 and is_verified column to 1 . If no record found, create one.

And last one is a very awesome method, which is useful for a more complicated scenarios.

firstOr

This method will accept a callback as the first argument and will run the callback if the query does not result any model instance.

You can customized the way you want the method. This method is very useful if firstOrFail, firstOrCreate or firstOrNew did not work for you.

I hope this series was helpful for you. If i forget to mention any other method, feel free to drop in comments and happy coding 🙂

Sharing is caring!

Related Post