How to Create Custom Class in Laravel 11 - TechvBlogs

How to Create Custom Class in Laravel 11

Craft reusable code and organize your Laravel application effectively by learning how to create custom classes in Laravel 11.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

3 months ago

TechvBlogs - Google News

Embrace the power of Laravel 11 by mastering the creation of custom classes with this comprehensive tutorial. The latest Laravel version boasts a more streamlined application skeleton, featuring enhancements like per-second rate limiting, health routing, and more. Dive into the details and learn how to leverage these updates to build a custom class seamlessly.

Creating a Custom Class in Laravel 11

Unlock the potential of Laravel 11's features with the addition of custom classes. A new artisan command facilitates this process. Execute the following command to initiate the creation of a new class in Laravel 11:

php artisan make:class {className}

Now, let's explore the step-by-step guide on how to create and utilize a custom class within a Laravel application.

Laravel Class Creation Example

Begin by crafting a "Helper" class using the following command:

php artisan make:class Helper

After creating the class, proceed to define the ymdTomdY() and mdYToymd() functions within the Helper.php file. Modify the code as follows:

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

With the Helper class established, proceed to incorporate these functions into your controller file:

Utilizing the Custom Class in a Controller

Navigate to the TestController.php file and employ the Helper class functions:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Helper;
  
class TestController extends Controller
{
    /**
     * Execute the helper class functions
     *
     * @return response()
     */
    public function index()
    {
        $newDate = Helper::ymdTomdY('2024-03-07');
        $newDate2 = Helper::mdYToymd('03/07/2024');

        dd($newDate, $newDate2);
    }
}

Output Verification

Upon executing the code, witness the following output:

"03/07/2024"
"2024-03-07"

Feel free to expand the capabilities of your custom class by adding more functions to suit your application's requirements.

This comprehensive guide empowers you to harness the full potential of Laravel 11 custom classes. Elevate your Laravel development experience by incorporating these practices into your projects. Happy coding!

Comments (0)

Comment


Note: All Input Fields are required.