54ba
54ba

Reputation: 53

converting string class name to an object in laravel

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

Upvotes: 0

Views: 3363

Answers (3)

mod7ex
mod7ex

Reputation: 948

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();

Upvotes: 0

Haq Nawaz
Haq Nawaz

Reputation: 482

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.

Upvotes: 0

matticustard
matticustard

Reputation: 5149

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);
    }
}

Upvotes: 1

Related Questions