Adding new models - McNamara84/ladis GitHub Wiki

Step 1: Create a new model template

Open your terminal and navigate to your Laravel project root directory. Run:

php artisan make:model MODELNAME

Example:

php artisan make:model City

Naming convention for Laravel models:

  • Singular
  • first letter capitalized
  • rest camel case

Step 2: Open the model file

Navigate to app/Models/ and open your newly created model file:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    //
}

Step 3: Define the table name if needed

Laravel expects table names to be plural and model names to be singular, because they are individual instances of PHP classes. If this causes problems (e.g., it will not work for Cities and City), please adjust it as follows:

class City extends Model
{
    use HasFactory;
    
    protected $table = 'cities';
}

Step 4: Define fillable or guarded properties

Protect against mass assignment vulnerabilities:

class City extends Model
{
    use HasFactory;
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array<string>
     */
    protected $fillable = [
        'federal_state_id',
        'name',
        'postal_code',
    ];
    
    // OR use guarded (but not both!)
    
    /**
     * The attributes that aren't mass assignable.
     *
     * @var array<string>
     */
    protected $guarded = ['id'];
}

Step 5: Define attribute casting if needed

Sometimes we cannot determine whether a data type in the controller has the same type as in the database. In our example city, we have exactly such a case. In the database, we store the postal code as a string, but it is very possible that we treat the postal code as integers in the controller. To avoid acidentally trying to store the postal code as numbers, we have to cast it:

protected $casts = [
    'postal_code' => 'string',
];

Step 6: Define relationships

For 1:1 relations

The library BelongsTo is essential

use Illuminate\Database\Eloquent\Relations\BelongsTo;

A City belongs to a Federal State:

public function federalState(): BelongsTo
{
    return $this->belongsTo(FederalState::class);
}

For 1:n relations

The library HasMany is essential

use Illuminate\Database\Eloquent\Relations\HasMany;

A Federal State has many Cities:

public function cities(): HasMany
{
    return $this->hasMany(City::class);
}
⚠️ **GitHub.com Fallback** ⚠️