Chapter 3 - Deep Dive into Model and Necessary Attributes
Hello Artisans, In this chapter we'll discuss about model and all the necessary attributes of model which can reduce our a lot of manual work. A model represents a single table in your database and provides an interface for interacting with that table's data. So if you already complete the Second chapter/section the you're good to go, if not my recommendation would be please complete the second one.
Now we'll see the usage of these attributes and how each of the attribute can reduce our works.
This attribute defines the name of the database table that the model represents. By default, Laravel will use the pluralized name of the model class as the table name. But in a case where you need to use the table which is goes totally different or doesn't contain the pluralized word then this attribute will take care of it. Suppose your model name is Attendance and according to Laravel it'll by default expect the ‘attendances’ table. But your table name is ‘employee_attendances’ then what you'll do. No worry, see the below example.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Attendance extends Model
{
use HasFactory;
protected $table = 'employee_attendances';
}
Now your Attendance model is representing the ‘employee_attendances’.
The primary key is a column in a database table that uniquely identifies each row in that table. By default, Laravel assumes that the primary key column is named id, but we can override this by setting the $primaryKey attribute on your model. So if we take the previous model “Attendance” as an example. Whenever we call it expects to use "id" as a primary key but we want to use "attendance_id" as a primary key. And that's why $primaryKey is there. Let' see the below example.
protected $primaryKey = 'attendance_id';
Note that if you use “attendance_id” as a primary key the you've to declare while using foreignId as well. See the below example
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('attendance_id')->constrained('attendances', 'attendance_id');
$table->text('body');
$table->timestamps();
});
The fillable property on a model is used to specify which attributes can be mass assigned using the create() method or the fill() or the update() method. Mass assignment is the process of setting multiple attributes on a model at once, typically using an array or a request object.
Here's an example of defining the fillable property on a User model:
class User extends Model
{
protected $fillable = [
'name',
'email',
'password',
];
}
and the in controller we can use it like these
$inputs = $request->all();
$inputs ['password'] = bcrypt($request->password);
$user = User::create($inputs);
//here inputs is an array which contains following data
['name' => "Tanvir",
'email'=> "tahmedhera@gmailcom",
'password' => "12345678" ,
]
And it'll save the data in database for you and also reduce some extra word by specifying each of attributes like following
$user = new User();
$user->name = 'Tanvir';
$user->email = "tahmedhera@gmailcom";
$user->password = bcrypt("12345678");
$user->save();
and this can be huge based on your data input.
The $guarded property on a model is used to specify which attributes should not be mass assigned using the create() method or the fill() method. Mass assignment is the process of setting multiple attributes on a model at once, typically using an array or a request object. i.e. we can say that it's a oppose of $fillable property. That's mean if a property is define in guarded property, we can not set by using create(), update() of fill() method.
Here's an example of defining the $guarded property on a User model:
class User extends Model
{
protected $guarded = [
'id',
'password',
'created_at',
'updated_at',
];
}
The $casts property on a model is used to specify which attributes should be automatically cast to certain data types when retrieved from the database or saved to the database. This can be useful for automatically transforming data between PHP and database-specific types, such as JSON or array values. Suppose we want to store a json value in our field. What we do is
blog->tags = json_encode($request->tags); //where tags is an array
because we cannot save array value to the database and if without doing encode if we try to save the we can se the below error like
“Array to string conversion”. And when we want retrieve we've to do below
$tags = json_decode($blog->tags,true);
//gives us this data ['php','laravel'.....]
But hangon, we ca don't need to do this all staff, we've the $casts attributes. Let's see how we can easily handle this situations with $casts attribute.
protected $casts = [
'tags' => 'array',
];
Now we don't need any json_encode() or json_decode(). Let's look at the below code snippet.
blog->tags = $request->tags; //where tags is an array but no need to json encode
and while retrieving
$tags = $blog->tags; // no need to json decode
//gives us this data ['php','laravel'.....]
These are methods on the model that are used to retrieve a value from an attribute before it is returned to the calling code. Accessors are named in a specific format: get[AttributeName]Attribute. For example, if you have an attribute named “first_name” and “last_name”, you can define an accessor method like below:
public function getNameAttribute()
{
return $this->first_name . ' '.$this->last_name;
}
Now everytime when we need to get the full name of a user, we need to call this way
$user->name //whihc gives the Tanvir Ahmed
We don't need to concate everytime like below
$user->first_name . ' '.$user->last_name
These are methods on the model that are used to set the value of an attribute before it is saved to the database. Mutators are named in a specific format: set[AttributeName]Attribute. For example, if you have an attribute named name, you can define a mutator method like this:
public function setNameAttribute($value)
{
$this->attributes['name'] = ucfirst($value);
}
We'll see the detail of each and every attributes which'll discuss in this chapter. That's it for today. See you in my fourth chapter. Happy coding 🙂 .