Thursday, April 13, 2017

Laravel one to many model relationship not working

I have a Booking model which can have many Service's.

I have defined the relationship in the Booking model like this:

<?php

namespace App;

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

class Booking extends Model
{

    /**
     * Get the services for the booking.
     */
    public function services()
    {
        return $this->hasMany('App\Service');
    }
}

Then in my BookingController I try to get all the services for the current booking like this:

    public function create()
    {       
        $services = Booking::find(1)->services;
        return view('bookings.create');
    }

I keep getting the error:

Trying to get property of non-object

Not sure what I'm doing wrong here. The foreign key relation is all set up fine. I have a booking_id column in the services table which references id on the bookings table.

Any help would be appreciated.



via user3574492

Advertisement