Reputation: 1027
This is with reference to this question :
Laravel Eloquent One to Many relationship
I tried the suggested way, but couldn't resolve. Please help. Below is the changes i have done :
Earlier :
//Route for Restaurants Page
Route::get('/home/restaurants',function(){
$restaurants = DB::table('restaurants')->simplepaginate(3);
return view('restaurants',['restaurants_data'=>$restaurants]);
});
Changed as per suggestion :
Route::get('/home/restaurants',function(){
// $restaurants = DB::table('restaurants')->simplepaginate(3);
$restaurants = \App\Restaurant::simplePaginate(3);
return view('restaurants',['restaurants_data'=>$restaurants]);
});
In Restaurant model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Restaurant extends Model
{
public function offer(){
return $this->hasMany('Offer');
}
}
In view, now I am trying to access it by dumping the values.
<?php
var_dump($restaurants_data->offer);
?>
After doing dd()
Upvotes: 1
Views: 98
Reputation: 35180
Firstly, I would suggest changing your Offer Relationship to:
public function offers()
{
return $this->hasMany(Offer::class, 'restaurant_ID', 'id');
}
The above assumes that the Offer
class and Restaurant
class are in the same namespace. If they're not please add the correct namespace or import the Offer
model in to the class.
Secondly, because you're paginating the results you will end up with a collection of Restaurant
models (even if there is only one), so you will need to loop through them to get access to the offers for each model. I would also suggest eager loading the results e.g.
Route
:
Route::get('/home/restaurants', function () {
$restaurants = \App\Restaurant::with('offers')->simplePaginate(3);
return view('restaurants', compact('restaurants'));
});
in your view:
@foreach($restaurants as $restaurant)
@foreach($restaurant->offers as $offer)
{!! dump($offer) !!}
@endforeach
@endforeach
{{ $restaurants->links() }}
Upvotes: 1
Reputation: 1593
Can you replace
$restaurants = \App\Restaurant::paginate(3);
and amend the blade code to say
<?php
foreach($restraunts_data as $resturant) {
if(count($restaurant->offer) {
print_r($restaurant->offer);
}
}
?>
Upvotes: 1
Reputation: 14863
You are using the models incorrectly. You run no queries and you attempt to run a static method on the Restaurant
class without selecting any restaurants. As far as I know is this not supported by Eloquent. If you look at the error message it complains that there are no property $offer
.
Try to run some query, and the select the related Offer
. This should work as expected.
For example:
$offers = \App\Restaurant::find(1)->offer;
This will return the many Offer
relations for the Restaurant
with ID 1.
Upvotes: 0