Laravel Call Function from Same Controller Example
Hello Artisan,
In this example, you will learn laravel call function from same controller. I would like to share with you laravel call another function in same controller. We will use how to call a controller function inside a controller in laravel. I explained simply step by step call function from same controller laravel.
Sometimes, we need to call a function in the same controller, then how you can do this? If you know PHP OOP then you don't need to think much. You can call controller function on same controller using "$this" key variable.
In this example, I will give you a very simple example of call a function from the same controller class. I will create getColorCode() private function for return color code from color name. that function i will call in index() method. Without any further ado, let's see below code example.
Example 1:
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$colorCode = $this->getColorCode('red');
$post = Post::create([
'name' => 'Silver',
'stock' => 100,
'bg_color' => $colorCode
]);
dd($post);
}
/**
* Write code on Method
*
* @return response()
*/
pivate function getColorCode($colorName)
{
$colors = [
'pink' => '#FFC0CB',
'plum' => '#DDA0DD',
'powderblue' => '#B0E0E6',
'purple' => '#800080',
'red' => '#FF0000',
];
return $colors[$colorName];
}
}
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
- How to Convert Collection to JSON in Laravel?
- How to Select Specific Columns in Laravel Eloquent Model?
- How to Get Columns Names from Model in Laravel?
- How to Create Model in Laravel using Command?
- Laravel Ajax GET Request Example Tutorial
- How to Get Environment Variable in Laravel React JS?
- Laravel React JS Pagination using Vite Example
- How to Automatically Generate Sitemap in Laravel?
- Laravel Google ReCaptcha V3 Tutorial Example
- Laravel Google ReCaptcha V2 Example Tutorial
- Laravel 9 Resource Route and Controller Example
- How to Create Controller in Laravel using Artisan Command?