DEV Community

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

How to Create Custom Class in Laravel 11

Hey there! Today, I'll walk you through creating your custom class in Laravel 11.

Custom classes are powerful tools for organizing your code and encapsulating logic. With Laravel's elegant structure, defining your classes is a breeze.

In this article, we'll create a custom class in laravel 11. In laravel 11 add new artisan command to create a custom class.

So, let's see laravel 11 creates a custom class and Laravel creates a class command.

You can create a custom class using the following command.

php artisan make:class {className}
Enter fullscreen mode Exit fullscreen mode

Example:

Now, we'll create a Helper class using the following command.

php artisan make:class Helper
Enter fullscreen mode Exit fullscreen mode

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'); 
    }
}
Enter fullscreen mode Exit fullscreen mode

After defining both functions, we'll utilize them in our controller file.

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Helper;

class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $newDate = Helper::ymdTomdY('2024-03-16');
        $newDate2 = Helper::mdYToymd('03/16/2024');

        dd($newDate, $newDate2);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

03/16/2024
2024-03-16
Enter fullscreen mode Exit fullscreen mode

You might also like:

Read Also: How to Publish Config Files in Laravel 11

Top comments (0)