Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent Relationship returning empty array

I'm New to laravel and I'm trying to achieve something very basic stuff but still getting stuck.

I have two models namely Post.php and Like.php

I'm trying to fetch all the likes linked to a post using eloquent relationship but it is returning an empty array. Here is my code-

Post.php

public function likes(){
  return $this->hasMany('App\Like');
}

Route.php

Route::get('/', function(){
  $posts = Post::all()->sortByDesc("post_id");
  return view('index')->with(['posts' => $posts]);
});

View.blade.php

@foreach($posts as $post)
  {{ $post->likes }}
@endforeach

What am I doing wrong here?

Update- likes table migration

public function up()
{
    Schema::create('likes', function (Blueprint $table) {
        $table->increments('like_id');
        $table->integer('post_id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->foreign('post_id')->references('post_id')->on('posts')->onDelete('cascade');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();
    });
}

Post Migration

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('post_id');
        $table->integer('user_id')->unsigned();
        $table->string('post_message');
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

Post Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

  public function user(){
    return $this->belongsTo('App\User');
  }

  public function likes(){
    return $this->hasMany('App\Like');
  }
}
like image 629
ujjwal verma Avatar asked Aug 14 '26 20:08

ujjwal verma


1 Answers

Laravel expects the primary key to be id, but you are using the custom post_id.

Specify it in your model and adjust the relationship:

class Post extends Model {
    protected $primaryKey = 'post_id';

    public function likes() {
        return $this->hasMany('App\Like', 'post_id');
    }
}
like image 110
Jonas Staudenmeir Avatar answered Aug 21 '26 02:08

Jonas Staudenmeir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!