How to use with laravel 5.6 in two models and get your data

0

Hello, I have a table called ReserveTable and another table called Fields I want to get the data of the model of the court:

public function reserva(){
    return $this->belongsTo('App\ReservaTable','idcanchas', 'idcanchas');
}

in my Controller I have the following:

$cancha = Cancha::where('iduser', $id)->with('reserva')->get();

    foreach ($cancha as $item)
    {
        echo $item->idcanchas . ': <br>';

        foreach ($item->reserva as $re)
        {
            echo $re->start_date . '<br>';
        }

    }

I want to send it to the view but it throws me the following error:

  

ErrorException (E_NOTICE)   Trying to get property of non-object

but if I do a dd ($ court) I get the following:

    
asked by Juan Jose 05.12.2018 в 19:22
source

1 answer

1

Hi, I can not comment on your question, but it sounds to me that you have more "users" and some (s) do not have reservations, so before running your foreach of the reservations, evaluate if each user has reservations with a " count "

$cancha = Cancha::where('iduser', $id)->with('reserva')->get();

foreach ($cancha as $item)
{
    echo $item->idcanchas . ': <br>';

    $numReservas = $item->reserva->count();

    if($numReservas > 0 )
    {
        foreach ($item->reserva as $re)
        {
            echo $re->start_date . '<br>';
        }
    }
}
    
answered by 06.12.2018 в 19:37