ItSolutionStuff.com

Laravel Call Function from Same Controller Example

By Hardik Savani • November 5, 2023
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Convert Collection to JSON in Laravel?

Read Now →

How to Select Specific Columns in Laravel Eloquent Model?

Read Now →

How to Get Columns Names from Model in Laravel?

Read Now →

How to Create Model in Laravel using Command?

Read Now →

Laravel Ajax GET Request Example Tutorial

Read Now →

How to Get Environment Variable in Laravel React JS?

Read Now →

Laravel React JS Pagination using Vite Example

Read Now →

How to Automatically Generate Sitemap in Laravel?

Read Now →

Laravel Google ReCaptcha V3 Tutorial Example

Read Now →

Laravel Google ReCaptcha V2 Example Tutorial

Read Now →

Laravel 9 Resource Route and Controller Example

Read Now →

How to Create Controller in Laravel using Artisan Command?

Read Now →