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
The
$fillable
attribute is used for themass assignment
protection in laravelThe
table
property is used when you not naming your model and table with the expected criteria for example if the table is calledusers
, so the model should beUser
otherwise you will need to specify it manuallysame also for
primaryKey
by default laravel will search for theid
columnSo in your case the table called
image_sliders
so your model should beImageSlider
First, you need to learn Laravel’s naming rules.
The best way is to create migrations at the same time as the model:
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.