The best way to add a method to all eloquent models

I have a method last()on one of my models.

class Article extends Model
{
    public function last()
    {
        return Article::orderBy('created_at', 'desc')->first();
    }
}

I need the same method on other models. What is the best way to do this?

+4
source share
1 answer

You can solve this problem in two ways.


With an abstract class that you distribute in all of your other models instead Model.

use Illuminate\Database\Eloquent\Model;

abstract class BaseModel extends Model
{
    public static function last() {
        return static::orderBy('created_at', 'desc')->first()
    }
}

so you will have the following

class Article extends BaseModel
{

}

Or more suitable, as you indicated, with a sign

trait Lastable {

    public static function last()
    {
        return static::orderBy('created_at', 'desc')->first();
    } 

}

What do you use in your desired classes.

class Article extends Model {
    use Lastable;
}
+5
source

Source: https://habr.com/ru/post/1653498/


All Articles