Inside this article we will see the concept of Laravel 10 Working with Eloquent Mutators and Accessors. Article contains classified information about How to work with Eloquent Mutators and Accessors in laravel application.
In Laravel, mutators and accessors allow us to alter data before it’s saved to and fetched from a database. To be more specific, the mutator allows us to alter data before it’s saved to a database. On the other hand, the accessor allows us to alter data after it’s fetched from a database.
We work with the concept of mutators and accessors methods into the Laravel model which is the central place of application.
Read More: How To Crop Image Before Upload in Laravel 10 Using Croppie.js
Let’s get started.
Laravel Installation
Open terminal and run this command to create a laravel project.
composer create-project laravel/laravel myblog
It will create a project folder with name myblog inside your local system.
To start the development server of laravel –
php artisan serve
URL: http://127.0.0.1:8000
Assuming laravel already installed inside your system.
Create Database & Connect
To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.
CREATE DATABASE laravel_app;
To connect database with application, Open .env file from application root. Search for DB_ and update your details.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_app DB_USERNAME=root DB_PASSWORD=root
Read More: Laravel 10 How To Create Signature Pad Using jQuery
Create Migration
Open project into terminal and run this command to create migration file.
$ php artisan make:migration create_products_table
It will create 2023_03_17_031027_create_products_table.php file inside /database/migrations folder. Open migration file and write this following code into it.
The code is all about for the schema of products table.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('name'); $table->integer('amount'); $table->text('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); } };
Run Migration
Back to terminal and run this command.
$ php artisan migrate
It will create products table inside database.
About Laravel Mutators
A mutator transforms an Eloquent attribute value when it is set. Mutators work when we save data inside database table.
Syntax to create mutators –
To define a mutator, define a set{Attribute}Attribute
method on your model where {Attribute}
is the “studly” cased name of the column which we want to get altered when saved.
Read More: SweetAlert2 jQuery Notification Plugin in Laravel 10 Tutorial
Create Model with Mutator
Back to project terminal and run this command to create model.
$ php artisan make:model Product
It will create Product.php file inside /app/Models folder.
Open Product.php and write this complete code into it.
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Product extends Model { use HasFactory; protected $fillable = [ 'name', 'amount', 'description' ]; // Mutator for Name column // when "name" will save, it will convert into lowercase public function setNameAttribute($value) { $this->attributes['name'] = strtolower($value); } }
- Mutator – setNameAttribute($value)
- It will alter value then assign to $this->attributes[‘name’]
- Other names mutator as – column name ( created_at ) -> setCreatedAtAttribute()
Concept
public function setNameAttribute($value)
{
$this->attributes['name'] = strtolower($value);
}
Note*: To create a model and migration using single command you can use this too.
$ php artisan make:model Product -m
-m for Migration
Next,
Mutator Usage in controller
Open project terminal and run this command.
$ php artisan make:controller ProductController
It will create ProductController.php inside /app/Http/Controllers folder.
Open ProductController.php file and write this code.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Product; class ProductController extends Controller { public function index() { $product = new Product(); $product->name = "Sample Product 1"; $product->amount = 12; $product->description = "Sample product created"; $product->save(); } }
Inside this above code we are only creating a sample product and save.
Once you save the data you will see in your database inside products table, product name will be in lowercase. If you pass any value, mutator will covert name value to lowercase and then save to database table.
About Laravel Accessors
An accessor transforms an Eloquent attribute value when it is accessed. It works when we fetch data from table.
Syntax to create accessor –
To define an accessor, create a get{Attribute}Attribute
method on your model where {Attribute}
is the “studly” cased name of the column.
Let’s create a accessor inside model.
Update Model with Accessor
Open Product.php and add this code into it.
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Product extends Model { use HasFactory; protected $fillable = [ 'name', 'amount', 'description' ]; // Accessor for Name column // when "name" will accessed, it will convert into uppercase public function getNameAttribute($value) { return strtoupper($value); } }
Concept
public function getNameAttribute($value)
{
return strtoupper($value);
}
Accessor Usage in Controller
Open ProductController.php controller file and add this method into it.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Product; class ProductController extends Controller { //... public function getProducts() { $products = Product::get(); foreach ($products as $product) { echo $product->name . "<br/>"; } } }
Inside this above code we are only fetching the database rows from products table.
Once you get data and print into your output screen you will see Product name will be in uppercase. This is because of data accessor. At runtime accessor will manipulate the value of which they created.
Mutators – Special methods of model which alters the data before save to database.
Accessors – Special methods of model which alters the data before output from database.
We hope this article helped you to learn about Laravel 10 Working with Eloquent Mutators and Accessors in a very detailed way.
Read More: Bootstrap Growl jQuery Notification Plugin in Laravel 10
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.