How to Create Custom Class in Laravel 11?
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- What’s New in Laravel 11: New Features and Latest Updates
- How to Install Laravel 11 Application?
- Laravel 10 REST API with Passport Authentication Tutorial
- How to Check Running Laravel App Environment?
- How to Truncate String in Laravel?
- Laravel Ajax GET Request Example Tutorial
- Laravel Send Scheduled Emails Tutorial
- Laravel Maatwebsite Excel Text Align Center Example
- How to Image Upload in Laravel Vapor?
- How to Setup Database in Laravel Vapor?
- Laravel Custom Login and Registration Example
- How to use Laravel Model Observers?
- Laravel Livewire Load More OnScroll Example
- How to Add Pagination with Union in Laravel?