Search code examples
laravel

creating model class for my table class in laravel


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!


Solution

  • 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