Getting Started With Default Sorting In Your Eloquent Models

Getting Started With Default Sorting In Your Eloquent Models

https://ift.tt/32M7LBI


Default Model Sorting package is a mini Laravel package I published recently. By default, Laravel Eloquent models return queries that are ordered by the id column of the model table.

With this package, you can set default order by in your Eloquent model so you don’t have to call the orderBy Eloquent builder.

<?php

Article::orderBy('title', 'asc')->get(); 


Article::all(); 

Installation

First you have to install this package via composer.

composer require stephenjude/default-model-sorting

Usage

Using the DefaultOrderBy trait of this package, you can set the default column you want to sort by.

For example, if you want to set the default order column for Article model (assuming you are building a blog). You will use the DefaultOrderBy trait and set the $orderByColumn property inside your Article model.

use Stephenjude/DefaultModelSorting/Traits/DefaultOrderBy;

class Article extends Model
{
    use DefaultOrderBy;

    protected static $orderByColumn = 'title';
}

Now your Article model queries will be ordered by title column in ascending order.

You can also set the $orderByColumnDirection property. This property is set to asc as the default value.

protected static $orderByColumnDirection = 'asc';

To set the global default $orderByColumnDirection property, publish the package configuration file.

php artisan vendor:publish --provider="Stephenjude\DefaultModelSorting\DefaultModelSortingServiceProvider" --tag="config"

Now you can update the configuration file as you desire.

return [    
    
    'order_by' => 'asc',
];

Under The Hood

This package is has a trait DefaultOrderBy that adds a default_order_by global scope to the boot() method of your Eloquent model.

 <?php
 ...
 protected static function boot()
 {
     parent::boot();

     
     $column = Self::$orderByColumn;

     
     $direction = isset(Self::$orderByColumnDirection)
            ? Self::$orderByColumnDirection
            : config('default-model-sorting.order_by');
     
     
     static::addGlobalScope('default_order_by', function (Builder $builder) use ($column, $direction) {
            $builder->orderBy($column, $direction);
        });
} 

If you don’t want to use the package, you can add this code to your Eloquent model.

If you find this package helpful please give it a start on Github.

programming

via Laravel News Links https://ift.tt/2dvygAJ

July 22, 2020 at 03:21PM