FAQ's and Trouble Shooting

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