In this post explain of laravel call function from same controller. I would like to share with you laravel call another function in same controller. Sometimes, we need to call function in the same controller. When working with Laravel controllers, there may be instances where you need to reuse functionality within same controller.
In this post guide, we will explore how to call a function in the same controller in Laravel with a simple example.
In this example, I will give you simple example of Laravel call function from same controller class. I will create getCodeColor() private function for color code from color name. That function call in data() method. Let’s see below example.
How to call function from same controller example
Example 1:
DemoController
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DemoController extends Controller
{
public function data(Request $request)
{
$colorCode = $this->getCodeColor('blue');
$list = ListItem::create([
'name' => 'test',
'is_active' => 1,
'bg_color' => $colorCode
]);
dd($list);
}
private function getCodeColor($name)
{
$colors = [
'pink' => '#FFC0CB',
'purple' => '#DDA0DD',
'blue' => '#0000FF'
];
return $colors[$name];
}
}
Laravel call function from same controller and How it work
- data method:Â This is the public method that will be accessed via route. It fetches color code using another method in the same controller.
- getCodeColor method: This is a private method that contains color code logic. By keeping private, it ensure the function is only accessible within the function Like DemoController.
Benefit of calling function in the same controller
- Code reusability: Reuse logic within the same controller without duplication.
- Maintainability: Makes the codebase easier to maintain and extend.
I hope this tutorial help you.