Laravel Custom Setter Tutorial Example


Share:
Published By: Admin, Published On: May 24, 2021, Category: Laravel 8 Laravel
Laravel Custom Setter Tutorial Example

Hey Artisan,

In this Article, i will learn you how to laravel custom setter tutorial in your laravel project.The laravel custom setter tutorial is so easy to use.so you can just follow my step by step and learn laravel custom setter tutorial.

So let's start to the example and follow to the my all step.

Solution
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
public function setPasswordAttribute($password)
{
    $this->attributes['password'] = bcrypt($password);
}
Step 1: Create a Employee model

Now Let's started our first step to create a Employee.php models and use this code.

Path : App/Models/Employee.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    use HasFactory;

    public $table = "employee";

    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'username',
        'password',
    ];

    /**
     * Write code on Method
     *
     * @return response()
     */
     protected $hidden = [
        'password',
    ];

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }
}

Step 2: Create Route

create a route in web.php file and use this code.

Path : routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('emp-create', [EmployeeController::class, 'create'])->name('emp.create');
Route::post('emp-store', [EmployeeController::class, 'store'])->name('emp.store');

Step 3: Create a EmployeeController

Next you can require to the EmployeeController so create a EmployeeController in just following command through.

php artisan make:controller EmployeeController
Path : app/Http/Controllers/EmployeeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employee;

class EmployeeController extends Controller
{

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('employee');
    }
 
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function store(Request $request)
    {

        $data = [
            'username' => $request->username,
            'password' => $request->password,
        ];

        $emp = Employee::create($data);
        dd($emp);
    }

}
Step 4: Create a employee Blade File

Next you can require to the employee.blade.php so create a employee.blade.php in your resources/views directory folder.

Path : resources/views/employee.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Custom Setters Tutorial - MyWebtuts.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body> 
   
<div class="container mt-5">
    <h1 class="text-center">Laravel Custom Setters Tutorial - MyWebtuts.com</h1>

    {!! Form::open(array('route' => 'emp.store','method'=>'POST')) !!}
        <div class="col-md-12">
            <div class="row mt-0">
                <div class="col-md-6">
                    <div class="form-group pl-3 pr-3">
                        <label>Username</label>
                        {{ Form::text('username', null ,['class'=>'form-control', 'placeholder'=>'User Name'] ) }}
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group pl-3 pr-3">
                        <label>Password</label>
                        {{ Form::password('password',['class'=>'form-control', 'placeholder'=>'Enter Password'] ) }}
                    </div>
                </div>
                <div class="col-md-12 text-center mt-2 mb-3">
                    <button type="submit" class="btn btn-success">Submit</button>
                </div>
            </div>
        </div>
    {!! Form::close() !!}
</div>
   
</body>
</html>

Ok, now you have to create some dummy records on employee table.

So, finally we are done with our code we can get below output.

php artisan serve
Browser url run : http://localhost:8000/emp-create
output:
App\Models\Employee {#293 ▼
  +table: "employee"
  #fillable: array:2 [▶]
  #hidden: array:1 [▶]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: true
  #attributes: array:5 [▶]
  #original: array:5 [▼
    "username" => "andy"
    "password" => "$2y$10$6PEjNQHqiVvm.3hPl64AKOlaWP.40rqL/Hobu/wy2cT.2dCvv/WQ6"
    "updated_at" => "2021-05-24 06:34:03"
    "created_at" => "2021-05-24 06:34:03"
    "id" => 8
  ]
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [▶]
}

It Will Help You...

Share: