Member-only story
How to use a function or a method from another controller in Laravel
SO, while working on a personal project, I was stuck on how to call a function from another controller — I know this is a bad practice in terms of code organization.
Note:
If you have a method in one controller that you need to access in another controller, then that’s a sign you need to re-factor. Consider re-factoring the method out in to a service class, that you can then instantiate in multiple controllers.
I will not recommend using this method on an organization’s project.
Okay, let’s continue…
So, I have two controllers namedParentController
and ChildController
. In ChildController
I have a method called respondValidationError
.
And I needed to access this method in ParentController
, I did this:
Child Controller
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use Response;use Illuminate\Http\Response as Res;use Illuminate\Pagination\LengthAwarePaginator as Paginator;class ChildController extends Controller{public function respondValidationError($message, $errors){ return $this->respond([ 'status' => 'error',