15
NovThe 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.
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);
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.
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);
}
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);
});
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();
Route::get('posts', PostController::class)
->middleware(['auth', CustomMiddleware::class])
// 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
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].
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'
*/
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
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 project