2

I've a PermissionController with a permission() function like below, and i want to call the permission() function in another controller. How can i call my permission() function to another controller ?

here my PermissionController

class PermissionController extends Controller
{
    public function permission(){
    $checkPermission = User::leftJoin('employees', 'employees.user_id', '=', 'users.id')
    ->leftJoin('positions', 'employees.position_id', '=', 'positions.id')
    ->leftJoin('divisions', 'employees.division_id', '=', 'divisions.id')
    ->where(function($query){
        $query->where('division_name', 'Sales')
                ->orWhere('division_name', '=', 'Project Management')
                ->orWhere('position_name', '=', 'Dept Head');
    })
    ->get();

    }   
}
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
rafitio
  • 550
  • 3
  • 15
  • 36
  • Possible duplicate of [Access Controller method from another controller in Laravel 5](http://stackoverflow.com/questions/30365169/access-controller-method-from-another-controller-in-laravel-5) – Raunak Gupta Dec 08 '16 at 13:01

5 Answers5

2

Create new Helper (e.g PermissionHelper.php) then move the funtion to it and call it where you want using :

PermissionHelper::permission();

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
2

You can call another controller's method, but this is terrible practice. Move you code to a model and call it with:

class PermissionController extends Controller
{
    public function permission()
    {
        $checkPermission = User::getEmployeePermissions();
    }
}

Do the same in other controllers' methods.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
1

I think your function should be in one of your model since you're only getting value.

This will me more relevant according to MVC.

Having it in your User model will let you use it on every instance of your application with a single call.

jeanj
  • 2,106
  • 13
  • 22
1

You can call your PermissionController's "permission" method this way :

app(PermissionController::class)->permission();

However, be aware that this method isn't a good idea at all.

You have multiple refactoring options available ranging from the use of a helper class, a method on the concerned model or using a laravel job.

Lukmo
  • 1,688
  • 5
  • 20
  • 31
1

Try to do like this

public function __construct(PermissionController $permission_controller)
{
  parent::__construct();
  $this->permission_controller = $permission_controller;
}

Call any method like this

$this->permission_controller->permission();
Komal
  • 2,716
  • 3
  • 24
  • 32