Andrew Tregubov
Andrew Tregubov

Reputation: 1

Is it possible to get data of related model inside current model in Laravel?

I'm building the Laravel app which using recursive url constructing. And I want to know is it possible to access data of the hasone related model within model to return constructed url direct to the view without interacting by controller.\

public function link(){
    var_dump($this->category());
    $url = ['news'];
    $url[] = $this->category()->url;
    $url[] = $this->url;
    return implode('/',$url);
}

Simple code example like this return this one

Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$url (View: /???/resources/views/common/news/full_preview.blade.php) (View: /???/resources/views/common/news/full_preview.blade.php) (View: /???/resources/views/common/news/full_preview.blade.php)

So is there any good way solve it by using just eloquent models, or it's only possible by using controllers and so on?

Upvotes: 0

Views: 1388

Answers (1)

Phiter
Phiter

Reputation: 14982

You shouldn't call $this->category() as a function. The function calls the relationship, not the related model.

To get the related model, remove the parenthesis.

$this->category->url

Here's the docs for relationships in laravel.

Upvotes: 5

Related Questions