15 1 0 4000 1 https://codeblock.co.za 300 true 0
How to Access a Controller Method From Another Controller in Laravel

How to Access a Controller Method From Another Controller in Laravel

0 Comments

In Laravel, sometimes is may be necessary to access a controller method from another controller. This is very easy to implement by simply including the controller with the required method in the controller that needs to access it.

Prerequisites

In my task manager app, I have a tasks controller which has a method that posts a notification to the task’s activity whenever a user updates the task.

I also have a milestones controller which allows me to create and attach milestones to a task. If a user completes a milestone objective, instead of creating a new method in the milestones controller, it’s easier to access the method that already exists in the tasks controller.

To get this to work, you must include the controller you need to access. Make sure to include the full path since, by default, Laravel will expect it to be a model path. As mentioned, I have two controllers: MilestonesController and TasksController.

The Tasks Controller (The Controller Being Accessed)

<?php
use App\Task;

class TasksController extends Controller
{
    public function postNotification($comment_content, $author){
       // Connect to DB and post notification
    }
}

The Milestones Controller (The Controller Requiring Access)

<?php
// Include the other controller in Milestones Controller
use App\Milestone;
use App\Http\Controllers\TasksController;

class MilestonesController extends Controller
{
    public function checkMilestone($id) {
       $milestone = Milestone::find($id);
       /* Update milestone etc. etc.  here */

       // if milestone is updated successfully
         $comment_content = "User marked milestone complete";
         $author = "System Bot";
      
         // Instantiate TasksController
         $tasks_controller = new TasksController;

        // Access method in TasksController
        $tasks_controller->postNotification($comment_content, $author);
    }
}

In the above example, the Milestones Controller is performing its function of updating the milestone then accessing the postNotification() method in the Tasks Controller to save the notification to the database.

Where To Use This Code

  • Include the controller class which has the method you require in the controller that needs to access the method.
  • Instantiate the controller class.
  • Call the method.

Is this still valid in 2021? Please let me know in the comments below.

Was This Helpful?

WooCommerce Releases Point of Sale
Previous Post
WooCommerce Releases Point of Sale. This is BIG!
How to Create Ajax Pagination and Filters With PHP
Next Post
How to Create Ajax Pagination and Filters With PHP

0 Comments

Leave a Reply