Hello Developers,
In this demonstration, you will learn about Accessors
and Mutators
in Laravel and how they work. Accessors and Mutators are custom-defined methods in Laravel. When you access data from the database then Accessor is used. When you save any value to the database, then Mutators are used.
Install Laravel Project In Your Environment
First, you need to go to your development workspace. My workspace is situated in D:/
drive. Open a command prompt and write the below code to install Laravel.
laravel new example-app
Database Configuration
After installing the project, open the project in your code editor. Now we have to configure the database credentials. As I am using the wamp server, I have to start the server and open the localhost/phpmyadmin
. In there I will create a database named example-app.
After that, add the credentials to the project .env file
/.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=example-app
DB_USERNAME=[USERNAME]
DB_PASSWORD=[PASSWORD]
Create Controllers, Models, Factory, Seeder
You can make all the elements like controllers, models, migration, and seeder. Request, policy by the following command:
php artisan make:model Product -mc
Now, open the product migration file to create a column in the product table. To show the demo, we will make only two fields name and stock. Add them to the migration file.
/database/migrations/[name]..._create_products_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('stock');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
After that, run the migrate command to create the table.
php artisan migrate
We need some demo data to show the accessor and mutators example. For that, we use a seeder and factory. To create ProductFactory
just run the below command:
php artisan make:factory ProductFactory
Paste the below code in the ProductFactory.php
file.
/database/factories/ProductFactory.php
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProductFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->name,
'stock' => rand(10,50)
];
}
}
To execute the ProductFactory.php
file, create a seeder file. To create a seeder run the below command:
php artisan make:seed ProductSeeder
The seeder file was created in the /database/seeders
location. Paste the following code in the ProductSeeder.php
/database/seeder/ProductSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Product;
use Illuminate\Database\Seeder;
class ProductSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Product::factory(50)->create();
}
}
Let's register the seeder in the DatabaseSeeder.php
/database/seeder/DatabaseSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Database\Seeders\ProductSeeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call(ProductSeeder::class);
}
}
Run the below seeder command to execute the seeder file.
php artisan db:seed
Let's create a function to fetch the data from the products table.
/app/Http/Controllers/ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function getProducts()
{
$products = Product::get();
foreach ($products as $product) {
echo $product->name . "<br/>";
}
}
}
Register this function to the route to get all the product names.
/routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;
/*
|--------------------------------------------------------------------------
| 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('list-product', [ProductController::class, 'getProducts']);
Accessor in the Model
Accessors are used to format the attributes when you retrieve them from the database. It works when we fetch data from the table of our database. To define an accessor, create a method. The method name should be like this format get[Attribute]Attribute. In the [Attribute] position, you need to write the column name. In our case, we will write an accessor to make the uppercased value from the data.
Open the Product.php
model and paste the below code:
/app/Http/Models/Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
public function getNameAttribute($value)
{
return strtoupper($value);
}
}
If we run the route of the list-product, then we get the Uppercased value in the browser. Run the below command and the URL in the browser:
http://127.0.0.1:8000/list-product
Output:
Mutator in the Model
Mutators are used to format the attributes before saving them in the database. A Mutator transforms an Eloquent attribute value when we store data in the database. The method name should be like this format set[Attribute]Attribute. In the [Attribute] position, you need to write the column name. In our case, we will write a mutator to make the lowercase value from the input.
/app/Http/Models.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
public function getNameAttribute($value)
{
return strtoupper($value);
}
public function setNameAttribute($value)
{
$this->attributes['name'] = strtolower($value);
}
}
Now create a function in the controller to set a tuple in the database. Open the ProductController.php
and write the below function:
public function setProduct()
{
$product = new Product();
$product->name = "Sample Product 1";
$product->stock = 12;
$product->save();
echo "Product Saved Successfully<br/>";
}
Register this function In the route file web.php
/routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
return view('welcome');
});
Route::get('list-product', [ProductController::class, 'getProducts']);
Route::get('product', [ProductController::class, 'setProduct']);
Run the below line to set a product in the database.
http://127.0.0.1:8000/product
Output:
That's how we create the accessor and mutators with proper examples. Practice more to use this in your project. Hope this short writing will help in the journey of your development.
Read More: Build simple CRUD REST API application using Laravel