How to Create Custom Class in Laravel 11?

By Hardik Savani September 4, 2024 Category : Laravel

Hi Developer,

In this post, we will learn how to create a custom class in laravel 11 framework.

Laravel 11 comes with a slimmer application skeleton. Laravel 11 introduces a streamlined application structure, per-second rate limiting, health routing, etc.

Laravel 11 added a new artisan command to create a custom class. we can use the following command to create a new class in laravel 11.

php artisan make:class {className}

You can create a new class and use it. I will show you how to create a class and how to use it in the laravel application. You can see the simple example:

Laravel Create Class Example:

First, you need to run the following command to create the "Helper" class. let's copy it:

php artisan make:class Helper

Next, we will create the ymdTomdY() and mdYToymd() functions in the Helper.php file. Then we will use those functions as a helper. so, let's update the following code to the Helper.php file.

app/Helper.php

<?php
  
namespace App;
  
use Illuminate\Support\Carbon;
  
class Helper
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public static function ymdTomdY($date)
    {
        return Carbon::parse($date)->format('m/d/Y'); 
    } 
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public static function mdYToymd($date)
    {
        return Carbon::parse($date)->format('Y-m-d'); 
    }
}

Now, we can use those functions in your controller file as below:

app/Http/Controllers/TestController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Helper;
  
class TestController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $newDate = Helper::ymdTomdY('2024-03-01');
        $newDate2 = Helper::mdYToymd('03/01/2024');

        dd($newDate, $newDate2);
    }
}

Output:

You will see the following output:

"03/01/2024"
"2024-03-01"

You can write more functions and use them.

I hope it can help you...

Shares