5eeker
5eeker

Reputation: 1027

Laravel Eloquent One to Many relationship

I have a Restaurants table and an Offers table. One restaurant may have multiple Offers. I am trying to create the relation between Restaurant - Offers using hasMany() method.

Table structure :

1) restaurant

2) offers

Code : In the Restaurant Model in am doing something like this

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;


class Restaurant extends Model
{


    public function offer(){

         return $this->hasMany('Offer');
    }
}

and in view, i tried printing the result using

below code in view

 foreach ($restaurants_data as $key => $value) {

         print_r($value->offer);
    ?>

Routes code :

Route::get('/home/restaurants',function(){
  $restaurants = DB::table('restaurants')->simplepaginate(3);
  return view('restaurants',['restaurants_data'=>$restaurants]);
});

enter image description here

But i am not getting the offers data, where am i going wrong. Thanks.

Upvotes: 1

Views: 343

Answers (2)

Ketan Solanki
Ketan Solanki

Reputation: 697

In the model change the code like this :

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Restaurant extends Model
{
    public function offer(){    
         return $this->hasMany('Offer','restaurant_ID','id');
    }
}

Upvotes: 0

Devon Bessemer
Devon Bessemer

Reputation: 35337

If you want the relationships defined in the Model, you have to use the Model:

$restaurants = \App\Restaurant::simplePaginate(3);

The query builder doesn't return model instances, it returns stdClass objects.

Upvotes: 1

Related Questions