0

i have this trait which i want to use dependency injection

<?php
 namespace App\Http\Controllers\Admin;
 trait ControllerTrait{


public function index($this->model $payroll){

    return $this->model->paginate(20);
   } 
}

the controller which uses this trait

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Payroll;

class PayrollController extends Controller
{
   use ControllerTrait;

   public $model = "Payroll";


 }

$model now is a string how to convert it to an object in calling index method of the trait

3 Answers 3

1

I don't believe dynamic type-hinting is possible, nor is it necessary in this instance.

I imagine this is what you're looking for.

namespace App\Http\Controllers\Admin;

trait ControllerTrait{
    public function index() {
        return ('\App\\'.$this->model)::paginate(20);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

why can't i use return ($this->model)::paginate(20); public $model = App\Payroll::class it gives an error
Try adding a preceding slash like public $model = \App\Payroll::class;. That works for me along with ($this->model)::paginate(20);.
0

You can use "call_user_func" function which can call function in your model.

public $model = "Payroll";
call_user_func($model . "::index");

Hope this will help.

Comments

0

I think you can use it as a string in php

$controllerClassName = 'TODOS\CONTROLLERS\\' . ucfirst($this->_controller) . 'Controller';

which is a string and i used it to create instances

$controller = new $controllerClassName();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.