FAQ's
Here are some common questions and issues that you may encounter while working with Laravel.
Models
How can I set the default sort column on a model?
Eloquent orders records based on their primary key, you can change the default sorting column by adding a global scope to the model.
protected static function booted() {
static::addGlobalScope('position', function (Builder $builder) {
$builder->orderBy('position');
});
}
How can I populate Laravel models without DB data?
Use the Sushi
package to populate Laravel models without DB data. It is also useful when you want
to populate your models with static data.
Using this package consists of two steps:
Add the Sushi
trait to a model.
Add a $rows
property to the model.
composer require calebporzio/sushi
class State extends Model
{
use \Sushi\Sushi;
protected $rows = [
[
'abbr' => 'NY',
'name' => 'New York',
],
[
'abbr' => 'CA',
'name' => 'California',
],
];
}
Now you can use the model as usual.
$states = State::all();
$stateName = State::whereAbbr('NY')->first()->name;
For more information, visit the Sushi GitHub repository
What is the Model $appends
Property: How Does It Work?
$appends
Property: How Does It Work?In Laravel, the $appends
property on an Eloquent model allows you to add custom attributes to the
model's array and JSON representations. These attributes are not stored in the database; they are
"computed" or "accessor" attributes, meaning they are generated at runtime based on some logic in
the model.
How It Works:
To use the $appends
property you;
-
Define an "accessor" in your model, which are methods that provide logic for computing the value of the custom attribute. These methods must follow the naming convention of
get{AttributeName}Attribute
.public function getFullNameAttribute() { return "{$this->first_name} {$this->last_name}"; }
-
After defining the accessor, you include the attribute name in the
$appends
property on the model. The attribute name should be in snake_case, matching how it would appear in the JSON output.class User extends Model { protected $appends = ['full_name']; public function getFullNameAttribute() { return "{$this->first_name} {$this->last_name}"; } }
Eloquent
What is the difference between the following two queries?
$query = auth()->user()->studentCourses; // Collection
$query = auth()->user()->studentCourses(); // Query Builder
The first query returns a collection of courses that belong to the user. The second query returns a query builder instance that you can further modify before executing the query.