I’m creating project with Laravel. I want to pull out user->name from subscription table which also has user_id column in it. I want to show the current user’s subscribers’ name from subscription table. But it shows error:
Property [subs] does not exist on this collection instance
here is my code.
This is from IndexController
public function home() {
$data = User::all();
return view("amvs.index", [
'users' => $data,
]);
}
This is from index.blade.php
<a href="#" class="list-group-item list-group-item-action border rounded-0">Subscriptions</a>
@foreach ($users->subs as $sub)
<span class="ms-2">{{$subs->name}}</span>
@endforeach
This is from user model
public function sub(){
return $this->hasMany('App\Models\Subscription');
}
I didn’t write anything in Subscription model. My subscription table
Schema::create('subscriptions', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('user_id');
$table->timestamps();
});
My user table
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
I’m a beginner so enlighten me.
>Solution :
The issue is that you’re trying to access a method on an Eloquent Collection which does not have any properties or methods relatated to your User or its sub relationship.
Additionally, consider using Eager Loading when accessing relationships, it is more performant and solves the N+1 query problem.
public function home() {
// access the authenticated User and load their subs relationship
$user = Auth::user()->with('subs')->first();
return view("amvs.index", [
'user' => $user
]);
}
Then to access the Users subs in your view:
@foreach ($user->subs as $sub)
{
<span class="ms-2">{{$sub->name}}</span>
}
However, you will want to change your subscriptions migration as the user_id field needs to be the same type as the id field on your users table.
Schema::create('subscriptions', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('user_id');
$table->timestamps();
});