Today, I will summarize some of the most commonly used tips in Laravel to easily search again when needed. There are things that I use very often but are still forgotten, or sometimes the deadline is too stressful to fix the bug but can’t find it, it is good to have saved data for easy reference, isn’t it? Ok, let’s get started
1. The classic Scopes
- Get the latest data for you to use as follows:
User::latest()->get();
But don’t forget this scope to get the list of users created_at
by created_at
sort in descending order, not updated_at
.
- Get the latest users list by any attribute:
last_login_at
User::latest('last_login_at')->get();
- Results returned with random order:
User::inRandomOrder()->get();
- Returns data with any one condition:
1 2 3 4 5 6 7 8 | User::when($request->query('sort'), function ($query, $sort) { if ($sort == 'new') { return $query->latest(); } return $query; })->get(); |
2. Custom Request Validate
Many times I often check the request sending data right in the Controller as follows:
1 2 3 4 5 6 7 8 9 | public function store(Request $request) { $validatedData = $request->validate([ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]); // The blog post is valid... } |
But until this Controller contains too much logic and coding it becomes difficult to maintain. So a better way is to split up so that the logic in the controller becomes less and from there I pushed the handling of validate requests to another class to perform this job.
Laravel has prepared for you if you want to execute it this way. Let’s see what to do:
php artisan make:request StoreArticlePost
When running this command, the StoreArticlePost class has the function to check the request when creating a post article, which will be saved in the following path: app/Http/Requests/
Add the validate to this class as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class StoreArticlePostRequest extends FormRequest { public function authorize() { return $this->user()->can('create.posts'); } public function rules() { return [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]; } } |
Now we do not declare the use of Illuminate Http Request in the controller anymore but instead
1 2 3 4 5 6 | use AppHttpRequestsStoreArticlePostRequest; public function store(StoreArticlePostRequest $request) { // The blog post is valid... } |
It takes a little bit more to look like a use case in a real project.
Addition 1:
If you notice the authorize()
function in StoreArticlePostRequest , this function will return an error 403 if the condition fails, so I need to fix a bit in the render function of app/Exceptions/Handler.php
1 2 3 4 5 6 7 8 | public function render($request, Exception $exception) { if ($exception instanceof IlluminateAuthAccessAuthorizationException) { // } return parent::render($request, $exception); } |
Addition 2:
When handling request errors, notification messages need to be returned, so in the StoreArticlePostRequest request we need to add the messages()
function as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class StoreArticlePostRequest extends FormRequest { public function authorize() { return $this->user()->can('create.posts'); } public function rules() { return [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]; } public function messages() { return [ 'title.required' => 'The title is required.', 'title.unique' => 'The post title already exists.', ... ]; } } |
Application:
Use in the validate form as follows:
1 2 3 4 5 | <input type="text" name="title" /> @if ($errors->has('title')) <label class="error">{{ $errors->first('title') }}</label> @endif |
3. Store the data in configs
Usually we treat static data in configs as follows:
I have model BettingOdds.php
1 2 3 4 5 | class BettingOdds extends Model { ... } |
There are configs section as follows config / bettingOdds.php
1 2 3 4 5 6 7 8 9 | return [ 'sports' => [ 'soccer' => 'sport:1', 'tennis' => 'sport:2', 'basketball' => 'sport:3', ... ], ]; |
When using : config('bettingOdds.sports.soccer');
How to make a BETTER alternative:
BettingOdds.php
1 2 3 4 5 6 7 8 9 10 | class BettingOdds extends Model { protected static $sports = [ 'soccer' => 'sport:1', 'tennis' => 'sport:2', 'basketball' => 'sport:3', ... ]; } |
When using :
BettingOdds::$sports['soccer'];
Why?
Because it’s easy to manage and handle new logic like this example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class BettingOdds extends Model { protected static $sports = [ 'soccer' => 'sport:1', 'tennis' => 'sport:2', 'basketball' => 'sport:3', ... ]; public function scopeSport($query, string $sport) { if (! isset(self::$sports[$sport])) { return $query; } return $query->where('sport_id', self::$sports[$sport]); } } |
Use scope: BettingOdds::sport('soccer')->get();
And so how you can extend it to depending on the next requirements of the project.
4. Use Collection instead of Array
A small example of Array is as follows:
1 2 3 4 5 | $fruits = ['apple', 'pear', 'banana', 'strawberry']; foreach ($fruits as $fruit) { echo 'I have '. $fruit; } |
We have a request to remove apples from the shipment, if any. To make this request, although there are many ways to do it, try to raise the problem that if you convert the array into a collection, is it easier to handle it?
1 2 3 4 5 | $fruits = collect($fruits); $fruits = $fruits->reject(function ($fruit) { return $fruit === 'apple'; })->toArray(); |
Result:
['pear', 'banana', 'strawberry']
The reject method is just one of the collection’s more than 100 built-in functions for convenience in handling the string of data upon request. You can explore and use the extensive collection.
5. Summary
Above, I present some good tips in Laravel along with practical examples, hope the article is useful for you who are looking for a good way to do the requirements of your current project or those who are new to learning about. Laravel. If you have a good way to do it, do not hesitate to add it below the comment so that I can update and refer to you. Happy Coding!