Table of Contents:
-
$table
-
$primaryKey
-
$fillable
-
$guarded
-
$casts
-
Accessors
-
Mutators
1. $table
The $table
attribute defines the name of the database table associated with the model. By default, Laravel uses the plural form of the model class name. However, if your table has a different name, you can specify it using the $table
property.
For example, if your model name is Attendance
, Laravel will expect a table called attendances
. But if your table is named employee_attendances
, you can specify it like this:
Now, the Attendance
model will represent the employee_attendances
table.
2. $primaryKey
The $primaryKey
attribute allows you to define a custom primary key for your model. By default, Laravel expects the primary key to be id
. You can override this by setting the $primaryKey
property.
For instance, if your primary key is attendance_id
instead of the default id
, you can specify it as follows:
When creating foreign keys in the database, make sure to use the correct primary key. For example:
3. $fillable
The $fillable
property specifies which attributes can be mass-assigned. It is used when creating or updating models using methods like create()
, fill()
, or update()
.
Here’s an example of how to use $fillable
in a User
model:
In your controller, you can create a new user like this:
This reduces the need to assign each property manually:
4. $guarded
The $guarded
Property is the opposite of $fillable
. It specifies which attributes should not be mass-assigned.
Here’s an example of using $guarded
in a User
model:
With $guarded
, you cannot mass-assign the attributes listed in the array.
5. $casts
The $casts
property allows you to automatically cast attributes to specific data types when they are retrieved or saved. This can be useful for handling data types like JSON or arrays.
For example, to store an array in a database field, you would normally need to use json_encode
before saving and json_decode
after retrieving the data. However, with $casts
, you can handle this automatically:
Now, you can save and retrieve the data without manually encoding or decoding:
6. Accessors
Accessors allow you to modify the value of an attribute before it is returned to the calling code. They follow a naming convention: get[AttributeName]Attribute
.
For example, if you have first_name
and last_name
attributes and want to combine them into a name
attribute, you can create an accessor like this:
Now, whenever you access $user->name
, it will automatically return the full name:
7. Mutators
Mutators allow you to modify an attribute's value before it is saved to the database. They follow a naming convention: set[AttributeName]Attribute
.
For example, if you want to ensure that the name
attribute is always capitalized before saving, you can create a mutator like this:
That’s all for today! In the next chapter, we’ll dive deeper into other important aspects of Laravel models. Happy coding! 😊