Nitish Kumar
Nitish Kumar

Reputation: 6276

Eloquent relationship in Laravel

I'm having following table structure:

Table Name - Users
    Column: id, name, email, etc

Table Name - Plugins
    Column: id, theme_id, type_id, code,

Table Name - Templates
    Column: id, theme_id, user_id, templatedata

Table Name - Userplugins
    Column: id, user_id, plugins_id, contents

Now I'm calling the route with id of the templates, in which templatedata has JSON data, i'm able to get Plugins code by following code in my blade file as:

@foreach($gettemplate as $renderer)

    {!! $plugins->find($renderer)->code !!}

@endforeach

but I'm unable to fetch contents in the UserPlugins table. Following is my controller where I'm trying to do so:

public function get_template($id)
{
    $template = Template::findOrFail($id);
    $gettemplate = json_decode($template->templatedata);
    $plugins = Plugins::all();
    $user = User::findorFail($id);
    return $user->userplugins()->contents;
    //return view('nitseditor.test', ['plugins' => $plugins, 'gettemplate' => $gettemplate, 'user' => $user]);
}

I've commented out my view just to check the output. I've defined the relationship in the model my App/User.php file contains:

public function userplugins(){

    return $this->hasMany('App\UserPlugin');
}

And in App\UserPlugin.php file I've:

protected $fillable = [

    'contents',

];

I'm getting the following error:

Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$contents

Please help me out, Thanks.

Upvotes: 0

Views: 218

Answers (1)

Chung
Chung

Reputation: 975

In the following line:

return $user->userplugins()->contents;

When you call $user->userplugins() that mean you call an relation method. It's will not return Eloquent Collection or Eloquent Object for you.

You need to call

$user->userplugins

to get collection of UserPlugin

However, when you call

return $user->userplugins->contents;

you will get error, becauese return $user->userplugins is an Eloquent Collection, you can not get contents from it.

You can get the contents of specific UserPlugin. For example, the first UserPlugin of user like:

return $user->userplugins()->first()->contents;

Upvotes: 1

Related Questions