jakub
jakub

Reputation: 43

Laravel: Set string as name for model

I´m working with polymorphic in Laravel 5.2. I want to set for the name of model string. There si code:

switch ($passport->element_type) {
            case 'Window':      
                $windows = Window::find($passport->element_id);
                break;
            case 'Floor':    
                $floor = Floor::find($passport->element_id);                    
                break;
            case 'Wall':
                $wall = Wall::find($passport->element_id);
            default:
                break;
        }
    };

You can see that variable "$passport->element_type" gives me the name of my model. I don´t want to do it with switch-case. Is it possible to do something like:

$passport->element_type::find($passport->element_id);

or how can I use the variable (element_type) as the name for model?

Upvotes: 0

Views: 589

Answers (3)

jakub
jakub

Reputation: 43

Thanks guys for help. Finally works, but I needed to add path:

$type = App::make('\\App\\'.$passport->element_type);

Upvotes: 0

Adiasz
Adiasz

Reputation: 1804

You need to set proper Model relations:

class Passport extends Model
{
    /**
     * Get all of the owning likeable models.
     */
    public function pasportable()
    {
        return $this->morphTo();
    }
}

class Window extends Model
{
    public function pasport()
    {
        return $this->morphOne('App\Pasport', 'pasportable');
    }
}

class Floor extends Model
{
    public function pasport()
    {
        return $this->morphOne('App\Floor', 'pasportable');
    }
}

class Wall extends Model
{
    public function pasport()
    {
        return $this->morphOne('App\Wall', 'pasportable');
    }
}

and next you can access to morph'ed object by:

$passport->element();
// or

Passport::find($id)->element();

and it should return Model of Floor, Wall or Window depending on element_type

Upvotes: 1

Samsquanch
Samsquanch

Reputation: 9146

Have you tried it?

If

$passport->element_type::find($passport->element_id);

doesn't work, I know that

$type = new $passport->element_type;
$type::find($passport->element_id);

will.

Upvotes: 0

Related Questions