Blog Detail

01

Apr
Top 10 Awesome Laravel Tips You Should Know in 2022  cover image

arrow_back Top 10 Awesome Laravel Tips You Should Know in 2022

Nowadays, Laravel is known as the best PHP framework for building modern, full-stack web applications. Laravel is incredibly scalable. It provides built-in support for fast, distributed cache systems like Redis, horizontal scaling, etc. Whether you are new to PHP or web frameworks or have years of experience, Laravel is a progressive framework that can grow with you. So in this article, I will share some amazing tips and tricks about laravel that can elevate your coding level and helps you in your coding journey.

When Searching for the first record, you can perform some actions

When searching for the first record, you want to perform some actions, when you don’t find it. firstOrFail() throws a 404 Exception.
You can use firstOr(function() {}) instead. Laravel got your covered.

$book = Book::whereCount('authors')
            ->orderBy('authors_count', 'DESC')
            ->having('modules_count', '>', 10)
            ->firstOr(function() {
                // THe Sky is the Limit ...
                
                // You can perform any action here
            });

Hide your custom command

If you don’t want to show a specific command on the artisan command list, set the hidden property to true.

class SendMail extends Command
{
    protected $signature = 'send:mail';
    protected $hidden = true;
}

You won’t see send:mail on the available commands if you typed php artisan.

Laravel skip method in scheduler

You can use skip in your commands to skip an execution

$schedule->command('emails:send')->daily()->skip(function () {
    return Calendar::isHoliday();
});

Get an existing key or insert a value if it doesn’t exist and return the value

In the Laravel 8.81 getOrPut method to Collections that simplifies the use-case where you want to either get an existing key or insert a value if it doesn’t exist and return the value.

$key = 'name';

// Still valid
if ($this->collection->has($key) === false) {
    $this->collection->put($key, ...);
}

return $this->collection->get($key);

// Using the `getOrPut()` method with closure
return $this->collection->getOrPut($key, fn() => ...);

// Or pass a fixed value
return $this->collection->getOrPut($key, $value='teacoders');

Force Laravel to use eager loading

If you want to prevent lazy loading in your app, you only need to add the following line to the boot() method in your AppServiceProvider:

Model::preventLazyLoading();

But, if you want to enable this feature only on your local development you can change the above code on that:

Model::preventLazyLoading(!app()->isProduction());

Directly convert created_at date to a human-readable format

Did you know you can directly convert created_at date to human-readable format like 1 minute ago, 1 month ago using the diffForHumans() function. Laravel eloquent by default enables Carbon instance on created_at field.

$post = Post::whereId($id)->first();
$result = $post->created_at->diffForHumans();

/* OUTPUT */
// 1 Minutes ago, 2 Week ago etc..as per created time

Check for the specific model was created or found

If you want to check for a specific model was created or found, use the wasRecentlyCreated model attribute.

$user = User::create([
    'name' => 'Oussama',
]);

// return boolean
return $user->wasRecentlyCreated;

// true for recently created
// false for found (already on your db)

Laravel Scout with a database driver

With laravel v9 you can use Laravel Scout (Search) with a database driver. No more where likes!

$companies = Company::search(request()->get('search'))->paginate(15);

Pass array to where method

Now in Laravel, you can pass an array to the where method.

// Instead of this
JobPost::where('company', 'laravel')
        ->where('job_type', 'full time')
        ->get();
// You can pass an array
JobPost::where(['company' => 'laravel',
                'job_type' => 'full time'])
        ->get();

Return the primary keys from the models collection

Did you know modelsKeys() eloquent collection method? It returns the primary keys from models collection.

$users = User::active()->limit(3)->get();

$users->modelsKeys(); // [1, 2, 3]

For more Laravel related Tips, Packages, and News, you can visit our blog.

Published at : 01-04-2022

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