Kirtesh Dusane
Kirtesh Dusane

Reputation: 21

Laravel eloquent with() returns null

namespace App;

use App\Model\Service\Area;
use App\Model\Bid\Service;
use Illuminate\Database\Eloquent\Model;

class Bid extends Model
{
    protected $table = "bid";

    protected $primaryKey = 'bid_id';

    protected $guarded = [];

    protected $with = ['services'];

    public function services() {
        return $this->hasMany(Service::class, 'bid_id');
    }

    public function area() {
        return $this->belongsTo(Area::class, 'area_id', 'area_id');
    }
}
namespace App\Model\Service;

use Illuminate\Database\Eloquent\Model;

class Area extends Model
{
    protected $table = "location_area";

    protected $primaryKey = 'area_id';

    protected $guarded = [];

    public function city()
    {
        return $this->belongsTo(City::class, 'city_id');
    }
}

Area table Migration and data

Bid table Migration and data

When I am trying to access

Bid::with('area')->find(BID_ID);

It is returning Null Query is firing wrong:

"select * from `location_area` where `location_area`.`area_id` in (0)"

But if I am doing like:

$bid = Bid::find(BID_ID);
dd($bid->area);

It returns Area table values. What is going wrong? Please Help me. I am having this problem for a long time. Thank You in advance :)

Upvotes: 0

Views: 1367

Answers (2)

Vishal Nakum
Vishal Nakum

Reputation: 11

you must be declared a method in your MID model

    public function area()
        {
            return $this->belongsTo(Area::class, 'bid');
        }

something like this after this, you access area in with()

Bid::with('area')->find(BID_ID);

Upvotes: 1

Yasin Patel
Yasin Patel

Reputation: 5731

Change this function in your Bid model :

 public function area() {
        return $this->belongsTo(Area::class, 'area_id');
    }

Upvotes: 0

Related Questions