Laravel call controller method from another controller

Laravel call controller method/function from another controller; Through this tutorial, you will learn how to call controller method/function from another controller function/method in laravel 10, 9, 8 apps.

Laravel call controller method from another controller

When you are creating a project in Laravel application. And then you have to call any or controller’s method/function in any controller function/method. so you will see how to call controller method/function from another controller in laravel 10, 9, 8:

Let’s say you have a TestController. And index method/function inside a TestController. Which is given:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class TestController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function exampleFunction()
    {
        return "Test Controller Text";
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    static function exampleFunctionStatic()
    {
        return "Test Controller Text";
    }
}

Again, Let’s say you have a HelloController. And index method/function inside a HelloController. Which is given:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;

  
class HelloController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        
  
        dd('hello');
    }
}

Now you want to call TestController’s method inside HelloController’s index method/function.So any call controller method can be called from any other controller in Laravel app.

You can see in the above example how TestController’s method is called from inside HelloController’s index method/function. Given below:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Http\Controllers\TestController;
  
class HelloController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $result = (new TestController)->exampleFunction();
  
        dd($result);
    }
}

Conclusion

Through this tutorial, you have learned how to call controller method/function from another controller function/method in laravel 10, 9, 8 apps.

Recommended Laravel Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *