skip to Main Content

I have created a table like:

public function up(): void
    {
        Schema::create('image_sliders', function (Blueprint $table) {
            $table->id('image_sliders_id');            
            $table->text('body')->nullable();
            $table->string('image');
            $table->boolean('status')->default(1);
            $table->timestamps();
        });
    }

Now I want to create respective Model class for my table.
I am confused that in some tutorial, it shows using protected $fillable...

class image_slider extends Model
{
    use HasFactory;
    protected $fillable = [
        'body',
        'image'
  

];
}

And in some tutorial it shows using table name and primary key name.

class image_slider extends Model
{
    use HasFactory;
    protected $table = 'image_sliders';
    protected $primarykey = 'image_sliders_id';
}

What is the difference between these two methods? Thank You!

2

Answers


  1. The $fillable attribute is used for the mass assignment protection in laravel

    The table property is used when you not naming your model and table with the expected criteria for example if the table is called users, so the model should be User otherwise you will need to specify it manually

    same also for primaryKey by default laravel will search for the id column

    So in your case the table called image_sliders so your model should be ImageSlider

    Login or Signup to reply.
  2. First, you need to learn Laravel’s naming rules.

    The best way is to create migrations at the same time as the model:

    php artisan make:model ImageSlider -m
    

    If you create the Eloquent model first, the table name will be determined automatically. Leave the ID as id. Laravel has general rules, so you should follow them without designing your own. If you use $table or $primarykey, you are breaking from Laravel’s standard rules.

    Convention over configuration also applies to Laravel.

    It’s all written in the official docs. Don’t believe unofficial tutorial articles, as they are all written by beginners who don’t understand Laravel.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search