Newing up models, in style
Although my recent submission for this idea to be integrated into the Laravel Framework was not particularly a popular request, I thought it might still interest others.
So recently I submitted an idea to improve the Laravel Framework by allowing for the instantiation (or "newing up") of models more expressively. Although it's a very small, and perhaps trivial thing to accomplish, I've had a number of occassions where it proved to be quite useful.
There are many ways the same thing can be achieved. You are probably aware of PHP's default way of instantiating a class, and then retrieving some details:
use App\Models\User;
$user = new User();
$fillable = $user->getFillable();
return $fillable;
Although this is fine, I am personally a fan of chaining methods to allow for a single line. This is what I personally use these days to accomplish this:
use App\Models\User;
return User::model()->getFillable();
Is it really worth it? That's pretty much up to you to decide. I found this little helper quite useful in a number of occasions, when I just wanted an instance of the model itself, regardless of any attributes.
It does offer a couple of benefits; it easier to find all occurrences of models being instantiated throughout your code (now you can just search for ::model()
instead) and it allows for the instantiation through class names (i.e. $class::model()
).
The method is defined as illustrated below. You can add this method to your base model, or use a trait or however you prefer.
/**
* Create a new Eloquent model instance.
*
* @param array $attributes
* @return static
*/
public static function model(array $attributes = []): static
{
return new static($attributes);
}
💡 In fact, did you know that Laravel actually provide a similar way of instantiating other classes, such as JsonResource::make()
or View::make()
? So my idea isn't entirely original after all. 🤔
Conclusion
In any case, it's a very simple way to "new up" a model without having to dance the parentheses parade 🕺 (I'm exaggerating, of course).