Best tips & good practices for Laravel

Tram Ho

1. Use local scopes when you need to query things

Laravel has a good way to write database queries using Query Builder.

This is pretty good. This helps me to focus on the logic, which is more accessible to me. But this code could be better written if we used local scopes.

Local scopes allow us to create Query Builder methods, which we can thread when trying to retrieve data. For example, instead of -> where (), we can use -> deliver () and -> pay () in a better way like this.

First, in our Order model, we should add some methods:

First, in the Order model, we should add some methods:

When declaring local scopes, you should use the correct naming of the scope [Something]. This way, Laravel will know that this is a scope and will use it in your Query Builder. Make sure you include the first argument inserted automatically by Laravel and the query builder instance.

For more dynamic access, you can use dynamic local scopes. Each scope allows you to pass parameters.

Later in this article, you will learn why you should use snake_case for database fields, but here is the first reason: Laravel uses the default where [Something] instead. previous scope. Instead of earlier, you can do:

Laravel will search the snake_case version of Something from where [Something]. If you have status in your DB, you will use the previous example. If you have shipping_status, you can use:

2. Use Requests files when needed

Laravel provides you with a powerful way to validate your forms. Whether it is a POST request or a GET request, it will not validate it if you need it.

You can validate this way in your controller:

But when you have too much code in your controller methods, that can be quite annoying. You want to reduce as much code as possible in your controller. At least, this is the first thing I think if I have to write a lot of logic. .

Laravel provides an easy way to validate requests by creating request classes and using them instead of old-fashioned Request classes. You just need to create your request:

In the app / Http / Requests / folder folder you will find your request file:

Now, instead of the Illuminate Http Request in your method, you should replace it with the newly created class:

The authorize () method must be boolean. If false, it will return 403, so make sure you catch it in the render () method of app / Exceptions / Handler.php:

The method missing here, in the request class, is the message () function, which is an array containing the messages that will be returned in case of validation failure:

To catch them in your controller, you can use the errors variable in your blade files:

In case you want to receive validation message for a specific field, you can do so later (it will return a false-boolean entity if validation passed for that field):

3. Magic scopes

When building everything, you can use the embedded magic scopes

Get results according to created_at, descending (descending):

Get results by field, descending (descending):

Get the random result of the field order, descending (descending):

Only run the query method if something is right:

Instead of when () you can use unless, as opposed to when ().

4. Use Relationships to avoid big queries (or bad-written ones)

Have you ever used a ton of links in a query just for more information? It is difficult to write those SQL statements, even with Query Builder, but models did that with Relationships. At first you will not be familiar, due to the high amount of information provided by the document, but this will help you better understand how things work and how to make your application run smoother.

See Relationships’ documentation here .

5. Do not store model-related static data in configs

What I like to do is store static data related to the model inside the model. I’ll show you. Instead of writing file: BettingOdds.php

In the file: config / bettingOdds.php

and access them using:

I would do like this:

and access them using:

Why? Because it is easier to use in subsequent operations:

Now we can use scopes:

6. Use collections instead of raw-array processing

In the past, we were accustomed to working with arrays in a rough way:

Now, we can use advanced methods that will help us process data in arrays. We can filter, transform, iterate and modify data in an array:

For more details, check out the extensive documentation on Collections .

When working with Query Builders, the -> get () method returns a Collection instance. But be careful not to confuse Collection with Query builder:

  • In Query Builder, we do not retrieve any data. We have many methods related to the query: orderBy (), where (), etc.
  • After we hit -> get (), the data is accessed, the memory is used, it returns a Collection instance instance. Some Query Builder methods are not available or they have names, but their names are different. .

If you can filter data at Query Builder level, do it! Don’t rely on filtering when it comes to Collection instances – you will use too much memory in some places and you don’t want to. Start your results and use index at DB level.

The article is translated from:

Share the news now

Source : Viblo