0
votes

[Laravel 5.7] I have a relationship between two entities (User, Voices) as Many-to-One relationship and it is not working in my project.

Users migration:

Schema::create('users', function (Blueprint $table) {
   $table->increments('id');
   $table->string('n_name');
   $table->string('n_photo');
   $table->string('n_gender');
});

Voices migration:

  Schema::create('voices', function (Blueprint $table) {
     $table->increments('id');
     $table->string('voice');
     $table->integer('n_id')->unsigned();
     $table->foreign('n_id')->references('id')
      ->on('users')->onDelete('cascade');
  });

Users Model:

class User extends Model
{
   public function voices(){
      return $this->hasMany(Voice::class);
   }
}

Voices Model:

class Voice extends Model
{
   public function user(){
      return $this->belongsTo(User::class, 'n_id');
   }
}

And the function "index" in my controller as below:

   public function index()
   {
      $user= User::all();
      $voices = $user->voices()::get(); -- error <described below>

      return view('index', compact('user', 'voices'));
   }

when I want to get the voices for each user it gives me an error says: "Method Illuminate\Database\Eloquent\Collection::voices does not exist."

My view looks like this:

@if($n->voices)
  @foreach($n->voices as $voice)
    <audio controls src="voices/{{$voice->voice}}"></audio><br/>
  @endforeach
@endif

I hope that I explained the issue very well and Ia waiting for a solution.

2

2 Answers

0
votes

Sorry for my previous message, I've just got the issue you had.

You can't fetch relationship on a COLLECTION of entities.

Your controller should look like so:

public function index()
{
    $user= User::with('voices')->get();

    return view('index', compact('user'));
}

And your blade should look like:

@foreach($users as $user)
    @foreach($user->voices as $voice)
    <audio controls src="voices/{{$voice->voice}}"></audio><br/>
  @endforeach
@endif

Does it work for you?

0
votes

Try in your controller:

$users = User::with('voices')->get();

I use it that way and it works properly for me.