Deep Dive into Model and Necessary Attributes Laravel

 Deep Dive into Model and Necessary Attributes

Hello Artisans, In this chapter we'll discuss the model and all the necessary attributes of the model which can reduce 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 you're good to go, if not my recommendation would be please complete the second one.


Table of Contents

  1. $table
  2. $primaryKey
  3. $fillable
  4. $guarded
  5. $casts
  6. Accessors 
  7. Mutators

Now we'll see the usage of these attributes and how each of the attributes can reduce our work.

$table

$table

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 a table that 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’ tableBut if 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’.

$primaryKey

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's see the below example.

protected $primaryKey = 'attendance_id';

Note that if you use “attendance_id” as a primary key 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();
});

$fillable

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 the 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' => "Soeng Souy",
        'email'=> "soengsouy@gmailcom",
        'password' => "12345678" ,
        ]

And it'll save the data in the database for you and also reduce some extra words by specifying each of the attributes like the following

				$user = new User();
        $user->name = 'Soeng Souy';
        $user->email = "soengsouy@gmailcom";
        $user->password = bcrypt("12345678");
        $user->save();

and this can be huge based on your data input.

$guarded

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 opposed to $fillable property. That means if a property is define as guarded property, we can not set it by using create()update() or 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',
    ];
}

$casts

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 the array value to the database and without doing encoding if we try to save we can see the below error like

Array to string conversion”. And when we want to retrieve we've to do below

$tags = json_decode($blog->tags,true);
//gives us this data ['php','laravel'.....]

But hang on, we ca don't need to do this for all staff, we've the $casts attributesLet's see how we can easily handle this situation 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'.....]

Accessors

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 the below:

public function getNameAttribute()
{
    return $this->first_name . ' '.$this->last_name;
}

Now every time 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 contact every time like below

$user->first_name . ' '.$user->last_name

Mutators

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 attribute which I'll discuss in this chapter. That's it for today. See you in my fourth chapter. Happy coding 🙂 .

Thank you for being so supportive!

Reactions

Post a Comment

1 Comments

CAN FEEDBACK

Emoji
(y)
:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:P
:o
:>)
(o)
:p
(p)
:-s
(m)
8-)
:-t
:-b
b-(
:-#
=p~
x-)
(k)