Blog Detail

15

Nov
Some Awesome tips and tricks for Laravel Development cover image

arrow_back Some Awesome tips and tricks for Laravel Development

The popularity of the Laravel framework is stimulating due to its unbelievable features. Laravel scores better than other web frameworks because of its advanced features and development tools that facilitate rapid web application development. Laravel also helps website developers simplify their development process with clean and reusable code.
Here in this article, I will share some awesome tips & tricks related to laravel development that many of you don’t know before.

Calculate Sum with Pagination

Suppose, you wanna calculate the sum of all records when you have only the PAGINATED collection. You’ve to do the calculation BEFORE the pagination but from the same query.

// How to get sum of post_views with pagination?
$posts = Post::paginate(10);
// This will be only for page 1, not ALL posts
$sum = $posts->sum('post_views');
// Do this with Query Builder
$query = Post::query();
// Calculate sum
$sum = $query->sum('post_views');
// And then do the pagination from the same query
$posts = $query->paginate(10);

Use groupBy on Collections with Custom Callback Function

If you want to group results by some condition that isn’t a direct column in your database, you can do that by providing a closure function.

For example, if you want to group users by day of registration, here’s the code:

$users = User::all()->groupBy(function($item) {
    return $item->created_at->format('Y-m-d');
});

⚠️ Notice :

It is done on a Collection class, so performed AFTER the results are fetched from the database.

Change API Token on users password update

It’s convenient to change the user’s API Token when its password changes.

Model:

public function setPasswordAttribute($value)
{
    $this->attributes['password'] = $value;
    $this->attributes['api_token'] = Str::random(100);
}

Preview Mailable

If you use Mailable to send an email, you can preview the result without sending, directly to your browser. Just return a Mailable as route result:

Route::get('/mailable', function () {
    $invoice = App\Invoice::find(1);
    return new App\Mail\InvoicePaid($invoice);
});

Using factories with relationships

When using factories with relationships, Laravel also provides magic methods.

// magic factory relationship methods
User::factory()->hasPosts(3)->create();

// instead of
User::factory()->has(Post::factory()->count(3))->create();

Pass middleware directly into the route without registering it

Route::get('posts', PostController::class)
    ->middleware(['auth', CustomMiddleware::class])

Laravel Request exists() vs has()

// https://example.com?popular
$request->exists('popular') // true
$request->has('popular') // false 

// https://example.com?popular=foo
$request->exists('popular') // true
$request->has('popular') // true

Artisan commands help

If you are not sure about the parameters of some Artisan commands, or you want to know what parameters are available, just type php artisan help [a command you want].

Transforming an array to CssClasses

use Illuminate\Support\Arr;

$array = ['p-4', 'font-bold' => $isActive, 'bg-red' => $hasError];

$isActive = false;
$hasError = true;

$classes = Arr::toCssClasses($array);


/*
 * 'p-4 bg-red'
 */

Filter route:list

New in Laravel 8.34: php artisan route:list gets additional flag –except-path, so you would filter out the routes you don’t want to see. See original PR

These are some useful tips and tricks related to laravel development, I hope that by following these tips you will enhance the performance of your code and usability. If you like them then please share your views on our Facebook, Twitter, or Instagram.

Facebook : https://www.facebook.com/CodeBrisk

Twitter: https://twitter.com/CodeBrisk

Instagram: https://www.instagram.com/codebrisk/

Published at : 15-11-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project