laravel example
About Us Blog Contact Us Request a quote

How to Create Custom Class in Laravel 12

How to Create Custom Class in Laravel 12

Install Laravel 12 App

Run below this command


composer create-project laravel/laravel example-app

Setup create a custom class using artisan command


php artisan make:class ChangeDateFormat

app/ChangeDateFormat.phplike as below code


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

create route

routes/web.php like as below code


<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DateFormatController;

/*
 * |--------------------------------------------------------------------------
 * | Web Routes
 * |--------------------------------------------------------------------------
 * |
 * | Here is where you can register web routes for your application. These
 * | routes are loaded by the RouteServiceProvider and all of them will
 * | be assigned to the "web" middleware group. Make something great!
 * |
 */

Route::get('/', function () {
    return view('welcome');
});

Route::controller(DateFormatController::class)->group(function () {
    Route::get('/date-format-change', 'index');
});

Create controller

Run below this command to create controller


php artsan make:controller DateFormatController

app\Http\Controllers\DateFormatController.php like as below code


<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\ChangeDateFormat;
  
class DateFormatController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $date1 = ChangeDateFormat::yyyymmddTOmmddyyyy('2024/03/21');
        $date2 = ChangeDateFormat::mmddyyyyTOyyyymmdd('03/21/2024');

        dd($date1, $date2);
    }
}

Run Laravel App:

Now Run your laravel 12 app after run these below commands


php artisan serve

Go to your web browser, hit this URL http://localhost:8000/whatsapp and see your laravel app output:

How to Create Custom Class in Laravel 12


Recent Posts