ホーム > Laravel > How to Use Service Classes in Laravel
Laravel

How to Use Service Classes in Laravel

Thank you for your continued support.
This article contains advertisements that help fund our operations.

⇨ Click here for the Table of Contents for Laravel articles

Here is an overview of how to use Service classes in Laravel.

Implementing a Service Class

Create a directory first.

It is common to create a folder in App\Services.

In this case as well,

App\Services

Create a folder like this.

Create a php file in the directory you just created.

App\Services\Test.php

This time the php file was created with this name.

Editing App\Services\Test.php

<?php

namespace App\Services;

class Test
{
    public function getTestUser()
    {
        dd('test');
    }
}

With this, you have created a service class.

Calling the Service Class

There are several ways to call it, here are three ways.

1. Method of using new

In the controller you want to use it, for example,

use App\Services\Test;

public function index()
{
    $test = new Test; // Instantiate the service class
    $user = $test->getTestUser(); // Call the function
    dd($user); //test
}

By using, instantiating the service class and calling it.

2. Reducing the instantiation description

use App\Services\Test;

public function index(Test $test) // Instantiate it here
{
    $user = $test->getTestUser(); // Call the function
    dd($user); //test
}

3. Using Facade

Regarding Facades, it seems clearer to write a separate article, so it has been summarized in a separate article.

What is Facade in Laravel? How to Implement Facade

Why Use Service Classes

If you write all the descriptions in the controller, it becomes a very difficult-to-read fat controller.

Controllers are recommended to make the descriptions as smart as possible and to write detailed logic separately.

Aim for skinny controllers!!

Issues with Service Classes

Service classes can be easily called from anywhere.

This can make it more complicated than controllers and become a factor in causing bugs.

Ultimately, if you do not operate it with clear rules, it will simply become code where

The controller's description is just moved to the service class

Summary

That's all.

I summarized how to use Service classes in Laravel.

Regarding the use of Service classes, I think the operating methods differ depending on the manager, but it is good to remember how to use them and apply them appropriately in that place.

I hope it can be helpful to someone.

For feedback or complaints, please contact me on Twitter DM.

That's it!

Popular Articles

Deploying a PHP 7.4 + Laravel 6 Project to AWS EC2

Implementing Breadcrumbs in Laravel using laravel-breadcrumbs

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!