7 things you need to know to make the most of Laravel Model
- Tram Ho
When I first started coding with Laravel, I felt that there were many things that could be done better when using with Model. After a while code with Laravel Model and find out, I found some interesting things that you can Use Model easily.
In this article I will give you 7 tips that every Laravel user should know to make the most of the Model.
1: How to create a Model by command
When creating a Model through the command, you can specify the Model directory to be created. Your job is to enter the directory name to save the Model in front of the Model’s name. This is really useful when you want to save the Model in a separate folder instead of the default saved in the app
folder
php artisan make:model Models/Product
2: Casting attributes
The $casts
attribute provides a convenient way to convert attributes into different data types. The $ casts attribute is an array whose key is the name of the attribute to be cast, and the value is the type of data you want to cast. Data types for cast support include: integer, real, float, double, string, boolean, object, array, collection, date, datetime, and timestamp.
For example, cast the is_admin
attribute stored in the database as an integer ( 0
or 1
) to a boolean
value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <? php App namespace; use Illuminate Database Eloquent Model; class User extends Model { / ** * Attributes that should be cast to native types. * * @var array * / protected $ casts = [ 'is_admin' => 'boolean', ]; } |
Now, the is_admin
attribute will always be cast to a boolean
when you access it, even if the value it is stored in the database is an integer
type:
1 2 3 4 5 | $ user = App User :: find (1); if ($ user-> is_admin) { // } |
3: Visibility
There will be times when you want to limit attributes like password
that are not displayed in array or JSON results after conversion. To do that, add the $hidden
attribute to the model: To declare an accessor, create a getFooAttribute function in the model with Foo the name of the column you want to access using the “camel” type. In this example, we will declare an accessor for first_name. Accessor will automatically be called by Eloquent when retrieving the value of the attribute first_name:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <? php App namespace; use Illuminate Database Eloquent Model; class User extends Model { / ** * The attributes that should be hidden for arrays. * * @var array * / protected $ hidden = ['password']; } |
Alternatively, you can use visible
properties to define a white-list of those attributes included in the array of models and JSON representation. All other properties will be hidden when the model is converted to an array or JSON:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <? php App namespace; use Illuminate Database Eloquent Model; class User extends Model { / ** * Các thuộc tính nên được hiển thị trong thời gian. * * @var array * / protected $ visible = ['first_name', 'last_name']; } |
This works like $fillable
and $guarded
attributes
4: Accessors
To declare an accessor, create a getFooAttribute
function in the model with Foo
as the name of the column you want to access using the “camel” type. In this example, we will declare an accessor for first_name
. Accessor will automatically be called by Eloquent when retrieving the value of the attribute first_name
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <? php App namespace; use Illuminate Database Eloquent Model; class User extends Model { / ** * Get the user's first name. * * @param string $ value * @return string * / public function getFirstNameAttribute ($ value) { return ucfirst ($ value); } } |
As you can see, the column’s original value is passed to the accessor, allowing you to change and return the value. To get this value, simply pass the attribute name to first_name
in model instance:
1 2 3 | $ user = App User :: find (1); $ firstName = $ user-> first_name; |
5: Mutator
To declare a mutator
, declare a setFooAttribute
function in the Foo
model which is the name of the column according to “studly”. So again, define a mutator
for the first_name
attribute. The mutator is automatically called when we set the value of the first_name
attribute in the model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <? php App namespace; use Illuminate Database Eloquent Model; class User extends Model { / ** * Set tên đầu người dùng * * @param string $ value * @return void * / public function setFirstNameAttribute ($ value) { $ this-> attributes ['first_name'] = strtolower ($ value); } } |
The mutator will receive the assigned value, allowing you to make arbitrary changes in the $ attributes of the Eloquent model. For example, we can assign attribute value first_name
to Sally
:
1 2 3 | $ user = App User :: find (1); $ user-> first_name = 'Sally'; |
6: Appending values
Sometimes, when casting models into an array or JSON, you can also add properties without fields stored in the database. To do so, it is necessary to declare an accessor
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <? php App namespace; use Illuminate Database Eloquent Model; class User extends Model { / ** * Get the administrator flag for the user. * * @return bool * / public function getIsAdminAttribute () { return $ this-> attributes ['admin'] == 'yes'; } } |
Once the accessor has been created, add the name of the attribute to the appends
attribute in the model. Note that the name of the attribute is in the “snake case” style, although the accessor is defined as “camel case”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <? php App namespace; use Illuminate Database Eloquent Model; class User extends Model { / ** * Các truy cập cho phép đăng nhập vào mẫu kiểu mẫu. * * @var array * / protected $ appends = ['is_admin']; } |
When the attribute is added in the appends
list, it will be added when converting into array or JSON. Attributes in the appends
array will also be sequentially visible
and hidden
in the model.
7: Touches
When a Model has a relationship with beLongsTo or beLongsToMany with another Model, for example a Comment belongs to a Blog, this case is very useful when updating the timestap
of the parent when the child is updated. This can be done by adding into the relationship attribute $touches
:
1 2 3 4 5 6 7 8 9 | Class Comment extends Model { protected $ touches = ['blog']; public function blog () { return $ this-> belongsTo (App Blog :: class); } } |
When Model Comment is updated, it will automatically update the update_at
attribute of the Blog
summary
The above are 7 things that I want to share with you to make the most of working with Model
Reference source
Source : viblo