1

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.

3
  • How do you call ->schedule_block() ? Commented Dec 25, 2018 at 6:26
  • Add ->toArray() at the end may be that helps to convert object into array Commented Dec 25, 2018 at 6:34
  • @Ijas schedule_block() is called from a controller with a with() Joshi - I am trying to get the object, not to make it into an array Commented Dec 25, 2018 at 10:39

1 Answer 1

2

try this one :

public function schedule_block() {
    $today = Carbon::today()->toDateString();
    return $this->hasOne(BlockDate::class)->where('date','=',$today);
}
Sign up to request clarification or add additional context in comments.

7 Comments

@NewProgrammer , is it working ? or you receives any errors ?
yes it is working, but I am confused. Relation hasOne does not point to the first entry of BlockDates with schedule_id, which I thought it will. How does it work?
block_dates() uses hasMany relation with BlockDate class , which will return array() , but as you want to get only one record as object , so i used hasOne relationship with BlockDate class , which will return Object.
technically Schedule class hasMany relation with BlockDate class, yes which is why it returns an array. I am just puzzled at how where() works for hasOne. Thank you for clarifying.
where will also work with hasMany , but it will return results as array not object
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.