Home Laravel How to Call Function from Same Controller in Laravel ?

How to Call Function from Same Controller in Laravel ?

by Shahriar Sagor

Hello dev, today now in this example, i will share with you laravel call function from the same controller. Here I would like to share with you an example of laravel call another function in the same controller. Now i will use here how to call a controller function inside the controller in laravel. Here I will explained the simply step by step call function from the same controller laravel.

Sometimes, we have to call a function in the same controller. Then here we know how you can do this? If you have a good understanding on PHP OOP then you don’t need to think much. We can easily call controller function on the same controller using “$this” key variable.

Now in this example, I will give you a very short and simple example of call a function from the same controller class. Here I will create the getColorCode() private function for the return color code from color name. So on that function i will call in index() method. Without any further i do.

let’s see the 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];
    }
}

Read Also: php artisan serve not working in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like