Using Laravel Facades to Improve Code Readability

Tolga Karabulut
1 min readJan 26, 2023

Laravel Facades allows you to make the usage of classes more readable and understandable. In this article, we will show you how to create a Facade and how to use it with a route and controller.

First, you need to create a folder app/Facades. In this folder, you will store your Facade classes. Then, create a file app/Facades/MyFacade.php and write a class like this:

<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;class MyFacade extends Facade {    protected static function getFacadeAccessor() {
return 'myclass';
}
}

In this class, you have to define the getFacadeAccessor method. This method specifies which class the Facade class represents. For example, we used the name 'myclass'.

Then, open the config/app.php file and add this line in the aliases array:

'MyFacade' => App\Facades\MyFacade::class,

This line defines the name of your Facade class and matches it with the real class.

Now, you can use your Facade class. For example, in a route:

Route::get('/', function () {
MyFacade::someMethod();
return view('welcome');
});

or in a controller:

class MyController extends Controller
{
public function index()
{
MyFacade::someMethod();
return view('welcome');
}
}

In this way, you can perform actions without knowing the name or details of the real class by using only the Facade class. This makes your code more readable and understandable.

The title and content of this article were created with “ChatGPT”.

Tolga Karabulut
tolga.karabulut@airalo.com
Airalo GSM | Senior PHP Developer

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Tolga Karabulut
Tolga Karabulut

Written by Tolga Karabulut

Software Development Specialist | @teknasyon Developer Team

No responses yet

Write a response