Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add method to all eloquent models

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

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

I want the same method on my other models. What the best way to do this?

like image 653
melihovv Avatar asked Mar 11 '23 05:03

melihovv


1 Answers

You can solve this one in two ways.


With an abstract class that you extend in all your other models instead of 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 appropriately, as you pointed out, with a trait

trait Lastable {

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

}

That you use in the desired classes.

class Article extends Model {
    use Lastable;
}
like image 173
Nicklas Kevin Frank Avatar answered Mar 24 '23 06:03

Nicklas Kevin Frank