First Eloquent Model

We create a new folder for every new model. So we focus on a model named Car, so we create a folder named Car.

Since we talk a about a model singular, I name my folders always singular, so 'Car', 'Brand', 'User' etc...

In this folder we create a new folder Events. In this Events folder we create 3 files:

See the chapter about Events on what to put in these files. First let's focus on the model itself.

Because of the namespacing we call our model simply Model. So we create a new file in the database\Eloquent\Models\Cars folder named Model.php.

<?php
namespace Db\Eloquent\Models\Car;

use Db\Eloquent\Models\Car\Events as Events;
use Db\Eloquent\Models\Base\Model as BaseModel;

class Model extends BaseModel
{
    protected $table = 'cars';
    protected $primaryKey = 'id';

    protected $fillable = [
        'hash', // record hashcode
        'name', // name of the car
        'year', // year on the market
        'engine' // engine
        'brand_id', // brand id
        ... other fields ...
        'cuser', // creation user
        'cdate', // creation date
        'muser', // modification user
        'mdate', // modification date
        'duser', // deleting user
        'ddate', // deletion date
        'active' // activation code, 1 = active, 0 = not
    ];

    protected $events = [
        'deleting' => Events\Deleting::class,
        'deleted' => Events\Deleted::class,
        'updating' => Events\Updating::class
    ];

    /**
     * Brand information from the Brand model
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function brand_info()
    {
        return $this->hasOne('Db\Eloquent\Models\Brand\Model', 'brand_id', 'id')
            ->where('active', 1);
    }

    /**
     * scope: inActive
     * @param $query
     */
    public function scopeIsActive($query)
    {
        $query
            ->where('active', '=', 1)
            ->get();
    }

    /**
     * scope: inActive
     * @param $query
     */
    public function scopeInactive($query)
    {
        $query
            ->where('active', '!=', 1)
            ->get();
    }

    // ... etc ...
}
Last update: Tue, 13 Sep 2022 14:32:15