How to Create Custom Class in Laravel 11?

08-Mar-2024

.

Admin

How to Create Custom Class in Laravel 11?

Hi Dev,

In this article, we'll explore the process of crafting a custom class within the Laravel 11 framework.

The latest version of Laravel, Laravel 11, presents a more concise application skeleton. Among its features are a refined application structure, per-second rate limiting, health routing, and more.

One notable addition in Laravel 11 is a fresh artisan command tailored for generating custom classes. To initiate the creation of a new class in Laravel 11, employ the following command.

php artisan make:class {className}

Creating and utilizing a new class in Laravel is a straightforward process. Let me guide you through the steps of creating a class and incorporating it into your Laravel application. Here's a simple example for you to follow:

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"

I hope it can help you...

#Laravel 11