get model using string

Zoe Chan :

I'm trying to access a Model in Laravel app through its Class Name, but I'm getting the following error:

Class 'Asset' not found

Though, I've already imported this Model. Here's my code:

<?php
namespace App\Services;
use App\Models\Asset as Asset;
use App\Models\Benefit\BenefitGroup as BenefitGroup;
use App\Models\Benefit\EmployeeDependent as EmployeeDependent;
use App\Models\Country as Country;
use App\Models\Employee\Education as Education;
use App\Models\Employee\EducationType as EducationType;
use App\Models\Employee\Employee as Employee;
use App\Models\Employee\EmployeeVisa as EmployeeVisa;
use App\Models\Employee\VisaType as VisaType;
use App\Models\Note as Note;
use App\Models\PaidTimeOff\Policy as Policy;
use App\Models\PaidTimeOff\TimeOffType as TimeOffType;
use Illuminate\Database\Eloquent\Model;
class ACLService
{
    public function getDefaultPermissions($roleType)
    {
        //Array to append all default permissions in single array without extra indexing
        $permissions=[];
        $models=['Asset', 'Employee', 'Education', 'EducationType', 'VisaType', 'EmployeeVisa', 'BenefitGroup', 'EmployeeDependent',
            'Policy', 'TimeOffType','Country', 'Note'];
        foreach ($models as $model) {
            $permissions=$this->getModelPermissions($model, $roleType, $permissions);
        }
    }
    public function getModelPermissions($model, $roleType, $currentPermissions)
    {
        $data=$model::getDefaultPermissionsForThisModel($roleType, $currentPermissions);
        return $data;
    }
}

If I pass

App\Models\Asset

instead of

Asset

then the error gets resolved but I don't want to pass data in this format because it'll increase the work amount if we ever get to change (in future) the Model's location in the project.

This is an incomplete project and we'll definitely change the models' location.

I'm looking for a cleaner solution.

Jerodev :

Use the ::class constant to get the correctly namespaced class name. This will also make it easier if you ever move the files. Smart IDE's will be able to detect the reference.

$models=[
    Asset::class, 
    Employee::class,
    ...
];

This presumes all classes have been imported at the top of your PHP file.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=9793&siteId=1