0

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?

2

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

8 Comments

No it doesn´t work. dd($type) return me "Window". But dd($type::find($passport->element_id)) throws error .. Class 'Window' not found.
Class 'Window' not found -- it's trying to work but it's not finding your model.
Yes, but dd(Window::find($passport->element_id)) works
don´t know why but already $type = new $passport->element_type; throws error Class "Window" not found. I think that problem is that it is looking for class 'Window' with apostrophes and it should only looking for class Window without apostrophes.
Try it with this: $type= "Window";, see if it still throws that error.
|
0

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

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

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.