Laravel Accessors and Mutators Tutorial in Laravel 11

 <?php


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string("user_name");
            $table->string("email", 50)->unique();
            $table->integer("salary");
            $table->date("dob");
            $table->string("password");
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};
Above File is database\migrations\2024_12_20_053051_create_users_table File





Below File is app\Models\User File
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Number;

class User extends Model
{
    public $timestamps = false;
    protected $table = "users";
    protected $fillable = ["user_name", "email", "salary", "dob", "password"];

    public function setEmailAttribute($value)
    {
        $this->attributes["email"] = strtolower($value);
    }

    // public function setUserNameAttribute($value)
    // {
    //     $this->attribute["user_name"] = strtolower($value);
    // }

    public function setPasswordAttribute($value)
    {
        $this->attribute["password"] = bcrypt($value);
    }

    public function getDobAttribute($value)
    {
        return date("d M Y", strtotime($value));
    }

    // public function getUserNameAttribute($value)
    // {
    //     return ucwords($value);
    // }

    public function getSalaryAttribute($value)
    {
        return Number::currency($value);
    }

    // Another method for Accessors and Mutators
    protected function UserName(): Attribute
    {
        return Attribute::make(
            get: fn(string $value) => ucwords($value),
            set: fn(string $value) => strtolower($value)
        );
    }
}






Comments

Popular posts from this blog

Eloquent Many to Many Relationship Tutorial in Laravel 11

Eloquent with JSON Data Columns Tutorial in Laravel 11

Blade Template Tutorial Three Template Inheritance in Laravel 11