How to create custom class in Laravel 11?

In this post explain of how to create custom class in Laravel 11. We will learn create custom class in Laravel 11. Custom class are powerful tools for organize your code and logic. Laravel 11 added a new artisan command to create a custom class.

What is custom class in Laravel?

Explain the concept of custom classes in Laravel, their role in organizing reusable logic. Use relatable example below.

We can use the following command to create custom class in Laravel 11.

php artisan make:class {classname}

You can create a new class and use it command. I will explain you how to create a class and how to use it in the laravel application. You can use and see easy example.

Laravel create class example

You need to run the following command to create custom class HelperTest class.

php artisan make:class HelperTest

Next, we will create the convert function in the HelperTest.php file. Then we will use those function as a helper. So following code to the HelperTest.php file.

app/HelperTest.php
<?php

namespace App;

class HelperTest
{
    /**
     * Create a new class instance.
     */

    public $string;
    public function __construct($string)
    {
        $this->string = $string;
    }

    public static function convert($string)
    {
        return strtoupper($string);
    }
}

Now, we can use those function in your controller like below.

app/Http/Controllers/DemoController.php
<?php

namespace App\Http\Controllers;
use App\HelperTest;
use Illuminate\Http\Request;


class DemoController extends Controller
{

    public function index()
    {
        $string = HelperTest::convert("hello users");
        dd($string);
    }
}
Output:
"HELLO USERS"

You can write more functions and use them.

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *