Laravel Call Function from Same Controller Example

By Hardik Savani November 5, 2023 Category : Laravel

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...

Tags :
Shares