NewProgrammer
NewProgrammer

Reputation: 295

how to return object instead of object in array

I am trying to return a response of an object which came from a collection array due to a relation of hasMany.

I have tried to do a return $block->where('date','=',$today)->first();

error said: Call to undefined method App\BlockDate::addEagerConstraints()

public function block_dates() 
{
    return $this->hasMany(BlockDate::class);
}

public function schedule_block() 
{
    $today = Carbon::today()->toDateString();
    $block = $this->block_dates();

    return $block->where('date','=',$today)->first();
}

schedule_block() should return an object of BlockDate. If I remove first(), it returns an array with the desired object in. I would like to just retrieve the object based on the relation. Any help is appreciated.

Upvotes: 1

Views: 927

Answers (1)

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

try this one :

public function schedule_block() {
    $today = Carbon::today()->toDateString();
    return $this->hasOne(BlockDate::class)->where('date','=',$today);
}

Upvotes: 2

Related Questions