Deep Dive into Model and Necessary Attributes Laravel

Deep Dive into Model and Necessary Attributes Laravel

Table of Contents:

  1. $table

  2. $primaryKey

  3. $fillable

  4. $guarded

  5. $casts

  6. Accessors

  7. 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:

<?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, 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:

protected $primaryKey = 'attendance_id';

When creating foreign keys in the database, make sure to use the correct primary key. For example:

Schema::create('comments', function (Blueprint $table) { $table->id(); $table->foreignId('attendance_id')->constrained('attendances', 'attendance_id'); $table->text('body'); $table->timestamps(); });

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:

class User extends Model { protected $fillable = [ 'name', 'email', 'password', ]; }

In your controller, you can create a new user like this:

$inputs = $request->all(); $inputs['password'] = bcrypt($request->password); $user = User::create($inputs);

This reduces the need to assign each property manually:

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

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:

class User extends Model { protected $guarded = [ 'id', 'password', 'created_at', 'updated_at', ]; }

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:

protected $casts = [ 'tags' => 'array', ];

Now, you can save and retrieve the data without manually encoding or decoding:

// Saving $blog->tags = $request->tags; // Retrieving $tags = $blog->tags; // No need to json_decode()

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:

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

Now, whenever you access $user->name, it will automatically return the full name:

$user->name // Returns "Tanvir Ahmed"

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:

public function setNameAttribute($value) { $this->attributes['name'] = ucfirst($value); }

That’s all for today! In the next chapter, we’ll dive deeper into other important aspects of Laravel models. Happy coding! 😊

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

1 Comments

CAN FEEDBACK
  1. s
    s
    :)
close