Blog Detail

11

Aug
10 Latest Laravel Tips and Tricks 2021 - Codebrisk cover image

arrow_back 10 Latest Laravel Tips and Tricks 2021 - Codebrisk

Laravel is an open-source PHP framework, which is robust and straightforward to understand. It is used for building a wide range of custom web applications. It supports a model-view-controller design pattern.

Laravel aims to provide an outstanding developer experience while giving powerful features such as thorough dependency injection, queues, and scheduled jobs, an expressive database abstraction layer, unit and integration testing, and many more. If you already have php knowledge then you can easily understand Laravel. Today I’ll share some great tips and tricks that will help you in intensifying your coding level.

1. Use Carbon with Only Hours

If you want to have a current date without seconds and/or minutes, use Carbon’s methods like setSeconds(0) or setMinutes(0).

echo now();
// 2020-04-20 08:12:34

echo now()->setSeconds(0);
// 2021-08-11 07:12:00


echo now()->setSeconds(0)->setMinutes(0);
// 2021-08-11 08:00:00

// Another way - even shorter
echo now()->startOfHour();

2. Generate Images with Seeds/Factories

Normally, We use Faker to generate fake text values in seeds and factories. But do you know that you can generate not only text values but also Images by Faker?

For example:
See image field here - it will generate 100x100 image:

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => bcrypt('password'),
        'remember_token' => Str::random(10),
        'Image' => $faker->image(storage_path('images'), 100, 100)
    ];
});

3. Use Older Laravel Version

If you want to use the older Laravel version instead of the newest Laravel, You can do this by running this command:

composer create-project --prefer-dist laravel/laravel project "7.*"

You can easily change 7.* to whichever version you want.

4. Simple Pagination

In pagination, if you need just “Previous/next” links instead of all the page numbers (and have fewer DB queries because of that), You can do this easily by changing paginate() to simplePaginate():

// Instead of 
$products = Product::paginate(8);

// Now you can do this
$products = Product::simplePaginate(8);

5. Send Notifications to Anyone

You can send Laravel Notifications not only to a specific user with $user->notify(), but also to anyone you want, via Notification::route(), with so-called “on-demand” notifications:

Notification::route('mail', 'Jhon@gmail.com')
        ->route('test', '123456')
        ->route('slack', 'https://hooks.slack.com/services/...')
        ->notify(new InvoicePaid($invoice));

6. Use @auth in Blade

Instead of an if-statement to check logged-in users, You can use the @auth directive in your blade file.

Old way:

@if(auth()->user())
    // The user is authenticated.
@endif

Latest:

@auth
    // The user is authenticated.
@endauth

The opposite is @guest directive:

@guest
    // The user is not authenticated.
@endguest

7. Check the view file exists

You can check if the View file exists before actually loading it.

if (view()->exists('admin.dashboard')) {
 // Load the view
}

You can even load an array of views, and only the first existing will be loaded.

return view()->first(['admin.dashboard', 'dashboard'], $data);

8. Create migration without underscore _ symbol

When you are running a make:migration command, you don’t necessarily have to write underscore _ symbol between parts, like create_users_table.

// with underscore _ symbol
php artisan make:migration create_users_table

You can enter the name into quotes and then utilize spaces instead of underscores.

// without underscore _ symbol
php artisan make:migration "create users table"

9. Use Auth::once()

Do you know that you c
an log in with the user only for One Request? You can easily do this by utilizing the method Auth::once(). No sessions or cookies will be used, which indicates this method may be applicable when building a stateless API.

if (Auth::once($credentials)) {
    //
}

10. Use @canany to check multiple permissions at once

Earlier, You use the @can directive to check if a user has a certain permission. Now, you can also check multiple permissions at once with the @canany directive.

@canany(['update', 'view', 'delete'], $blog)
    // The current user can update, view, or delete the blog post

@elsecanany(['create'], \App\Blog::class)
    // The current user can create a blog post
@endcanany

I hope that these tips and tricks will help you in your laravel journey and enhance your coding skills. You can also view my previous article on laravel tips here.

Published at : 11-08-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