Blog Detail

15

Jul
Some Tips & Tricks to Upgrade Your Laravel Code cover image

Some Tips & Tricks to Upgrade Your Laravel Code

Laravel aims to provide an incredible developer experience while providing powerful peculiarities such as thorough dependency injection, a strong database abstraction layer, queues and scheduled jobs, unit and integration testing, and much more. If you are new to PHP or web frameworks or an experienced developer, Laravel is a framework that can grow with you.

When working with the Laravel framework, you can employ some tips & tricks to upgrade your coding level and make your application more vivid and your code more refined. The more you utilize certain layout principles and best practices, the more you will progress as a developer. In this article, I will discuss some tips and tricks that can help you in escalating the level of your laravel application. Here we go!

Eloquent where date methods

In Laravel Eloquent you should use date with functions whereDay(), whereMonth(), whereYear(), whereDate() and whereTime().

$flights = Flight::whereDate('created_at', '2021-10-31')->get();

$flights = Flight::whereMonth('created_at', '10')->get();

$flights = Flight::whereDay('created_at', '30')->get();

$flights = Flight::whereYear('created_at', date('Y'))->get();

$flights = Flight::whereTime('created_at', '=', '12:10:00')->get();


Eloquent query scopes

Frequently, when utilizing Eloquent ORM in our Laravel applications, we need to match certain conditions when working with data. For example, consider this query:

$active_admins = User::where('is_active', '=', 1)->where('is_admin', '=', 1)->get();

You can use this scope in many places throughout your laravel application. So if you wanted to make your code more precise and not be monotonous, then you can use query scopes.

For example, Here we would create this function in our User Model.

public function scopeActive($query)
{
    return $query->where('is_active', '=', 1);
}

public function scopeAdmin($query)
{
    return $query->where('is_admin', '=', 1);
}

Now by using query scopes, Your query will look like this.

$active_admins = User::active()->admin()->get();

No timestamp columns

If your Database table doesn't include timestamp fields created_at and updated_at, then you can define that the Eloquent model wouldn't use them. You've to use the "$timestamps = false" property in your model.

class Product extends Model
{
    public $timestamps = false;
}

No Need to Convert Carbon

If you're utilizing whereDate() to monitor today's records, you can employ Carbon's now() and it will automatically be converted to date. No need to do ->toDateString().

// Instead of
$todayOrders = Order::whereDate('created_at', now()->toDateString())->get();

// No need to convert, just use now()
$todayOrders = Order::whereDate('created_at', now())->get();

Storing Array Type into JSON

If you have an input field that accepts an array and you have to save it as a JSON, you can utilize $casts property in your model. Here "files" are a JSON attribute.

protected $casts = [
    'files' => 'array',
];

So you can save it as a JSON, but when you've fetched it from Database, it can be utilized as an array.

Set Column Value Automatically on Model create

When you are creating a new record, there are some circumstances in which you desire to set a specific column automatically. To accomplish this, you can utilize the model's creating event inside the boot method of the model.

Here's an example of a Product Model:

class Product extends Model {
    protected static function boot()
    {
        parent::boot();

        Product ::creating(function($model) {
            $model->active= 0;
        });
    }
}

Eloquent has() deeper

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

// Student-> hasMany(Course::class);
// Course-> hasMany(Rating::class);

$students= Student::has('courses.ratings')->get();

Update or Create

When you are working with databases it's common to check that a specific record exists, and then update it, or create a new record.

For example:

$flight = Flight::where('departure', 'Los Angeles')
    ->where('destination', 'San Jose')
    ->first();

if ($flight) {
    $flight->update(['price' => 199, 'discounted' => 1]);
}

 else {
    $flight = Flight::create([
        'departure' => 'Los Angeles',
        'destination' => 'San Jose',
        'price' => 199,
        'discounted' => 1
    ]);
}

Instead of this long code, you can do it in one sentence by using the Eloquent method updateOrCreate():

$flight = Flight::updateOrCreate(
    ['departure' => 'Los Angeles', 'destination' => 'San Jose'],
    ['price' => 199, 'discounted' => 1]
);

I hope these tips and tricks will assist you in building your laravel web application and take your code to a higher level.

Published at : 15-07-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.

web application development client
web application development client
web application development client
web application development client
web application development client

Launch project