jeudi 20 février 2020

get model using string

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.





Aucun commentaire:

Enregistrer un commentaire