Defining a Model Laravel

Models connect to your database. Model is always a singular name, while the database table is the plural name of the model. See example below

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
}

This model is named Post which means it automatically will look for a database table named “posts” in lowercase. The default ID it will look for will be named “id”.

You can change the defaults of the table name and id name like this:

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    protected $table = 'posts_table';
    protected $primaryKey = 'post_id';
}

Leave a Reply

Your email address will not be published. Required fields are marked *