5 Tips to Simplify Laravel Code

Reading Time: 3 minutes

1. Simplify if/else statements

When writing methods or functions that use if/else statements to check for a condition, we can clean up the function or method by using the shorthand version of a simple if/else like so:

2. Use Laravel’s exists() instead of count() to verify a model instance exists.

When querying the database and trying to access a model instance, sometimes our Eloquent queries will come back empty or null. The first instinct is to check if the count of models is 0, and if it is not, then something exists, but Laravel provides an out-of-the-box method for checking if a model instance exists.

3. Use modelKeys() to get Primary Keys instead of pluck()

When we are accessing a model and trying to get the primary keys or the model IDs, the easiest way to do that is to use pluck() to get specific fields. But if all you want to access are the model keys or primary keys and nothing else (for syncing or attaching to another model perhaps), you can use the built-in method modelKeys()

4. Don’t create unnecessary variables, and try to return values directly

When learning to code, we get in the habit of creating variables for everything, and rightfully so. We need to be able to store and track data across methods, functions, and classes, but sometimes it’s not necessary to create a variable we aren’t going to change or modify later on in the method. Simplify your code by returning values directly when you can, like below.

5. Take advantage of Laravel Collections instead of manually manipulating arrays

Laravel’s Collections have dozens of available methods that simplify many processes that would otherwise have to be done manually with an array or multiple arrays. Take, for example, adding an element to the end of an array:

Functionally, these two approaches are the same, but using Laravel’s Collections gives you access to a multitude of methods you can perform on individual collections or items in a collection. Here are some examples:

These are only a small sample of the available methods in Laravel’s Collections, but they accomplish tasks that Arrays either can’t accomplish without a custom function, or are difficult to accomplish in a straightforward manner.

I hope you find these tips helpful! For more Laravel tips, check out Laravel-code.tips