Blog Detail

18

Oct
Some Useful Tips And  Tricks to Boost Laravel Code cover image

arrow_back Some Useful Tips And Tricks to Boost Laravel Code

There are a variety of tools and frameworks available to you when building a web application. However, Laravel is the best alternative 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 great tips and tricks about laravel that can enhance your coding level and give you a boost as you take your expertise to the next level.

Don’t Filter by NULL in Collections

You can filter by NULL in Eloquent, but if you’re filtering the collection further - filter by an empty string, there’s no “null” in that field anymore.

// This works
$messages = Message::where('read_at is null')->get();

// Won’t work - will return 0 messages
$messages = Message::all();
$unread_messages = $messages->where('read_at is null')->count();

// Will work
$unread_messages = $messages->where('read_at', '')->count();

Load Count on-the-fly

In addition to Eloquent’s withCount() method to count related records, you can also load the count on-the-fly, with loadCount():

// if your Product hasMany Reviews...
$product= App\Product ::first();

$product->loadCount('reviews');
// Then you get access to $product->reviews_count;

// Or even with extra condition
$product->loadCount(['reviews' => function ($query) {
    $query->where('rating', 5);
}]);

Send Notifications to Anyone

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

Notification::route('mail', 'jhon@example.com')
        ->route('nexmo', '928299173')
        ->route('slack', 'https://codebrisk.slack.com/services/...')
        ->notify(new InvoicePaid($invoice));
/

Artisan command parameters

When creating the Artisan command, you can ask the input in a variety of ways:
$this->confirm() , $this->anticipate() , $this->choice() .

// Yes or no?
if ($this->confirm('Do you wish to continue?')) {
    //
}

// Open question with auto-complete options
$name = $this->anticipate('What is your name?', ['Jhon', 'Doe']);

// One of the listed options with default index
$name = $this->choice('What is your name?', ['Jhon', 'Doe'], $defaultIndex);

API Resources: With or Without “data”?

If you use Eloquent API Resources to return data, they will be automatically wrapped in data. If you want to remove it, add JsonResource::withoutWrapping(); in app/Providers/AppServiceProvider.php.

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        JsonResource::withoutWrapping();
    }
}

Single Action Controllers

If you want to create a controller with just one action, you can use the __invoke() method and even create invokable controller.

Route:

Route::get('user/{id}', 'ShowProfile');

Artisan:

php artisan make:controller ShowProfile --invokable

Controller:

class ShowProfile extends Controller
{
    public function __invoke($id)
    {
        return view('user.profile', [
            'user' => User::findOrFail($id)
        ]);
    }
}

Jobs can be used without queues

Jobs are discussed in the Queues section of the docs, but you can use Jobs without queues, just as classes to delegate tasks to. Just call $this->dispatchNow() from Controllers

public function approve(Article $article)
{
    //
    $this->dispatchNow(new ApproveArticle($article));
    //
}

Eloquent has() deeper

You can use Eloquent has() function to query
relationships even two layers deep!

// Author -> hasMany(Book::class);
// Book -> hasMany(Rating::class);
$authors = Author::has('books.ratings')->get();

Rename Pivot Table

If you want to rename the pivot word and call your relationship something else, you just use ->as(‘name’) in your relationship.

Model:

public function podcasts() {
    return $this->belongsToMany('App\Podcast')
        ->as('subscription')
        ->withTimestamps();
}

Controller:

$podcasts = $user->podcasts();
foreach ($podcasts as $podcast) {
    // instead of $podcast->pivot->created_at ...
    echo $podcast->subscription->created_at;
}

Combine Two “whereHas”

In Eloquent, you can combine whereHas() and orDoesntHave() in one sentence.

User::whereHas('roles', function($query) {
    $query->where('id', 1);
})
->orDoesntHave('roles')
->get();

These are some useful tips and tricks related to laravel that can help you to improve your code, 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 : 18-10-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