Pankaj Sharma
Pankaj Sharma

Reputation: 41

How to call Controller Method in a Controller in a different namespace in laravel

I want to call a function of CommonController in PostsController.

PostsController is in Posting namespace

PostController: App\Http\Controllers\Posting\PostsController
CommonController: App\Http\Controllers\CommonController

I tried this code but it did not work in PostingController, it is a small code from my PostingController

namespace App\Http\Controllers\Employer;
use App\Http\Controllers\CommonController;

class PostsController extends Controller
{
    public function myFunction(Request $request, $id){
        $commonControllerObj = new CommonContoller;
        $result = $commonControllerObj->commonCallingFunction($id);
    }
}

but it did not work, its giving error

Class 'App\Http\Controllers\Posting\CommonContoller' not found

Upvotes: 1

Views: 448

Answers (1)

Quynh Nguyen
Quynh Nguyen

Reputation: 3009

The first your namespace is wrong

namespace App\Http\Controllers\Posting;

The second you can call another Controller like this

app('App\Http\Controllers\CommonController')->commonCallingFunction();

This will work, but this is bad in terms of code organisation

You can extends Controller like this

use App\Http\Controllers\CommonContoller;

class PostsController extends CommonContoller
{
    public function myFunction(Request $request, $id){
        $result = $this->commonCallingFunction($id);
    }
}

Upvotes: 3

Related Questions