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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With