Home Laravel eloquent two has many relation
Reply: 2

Laravel eloquent two has many relation

Brian lee
Brian lee Published in 2015-06-20 21:02:06Z

I've tried it too many times but I still can't get it. I am trying to make a custom tour app with laravel. I have 3 models which is User - Request - Offer User has many requests, request has many offers but the offer and request both belong to user, it is because of the user table have two roles, one as a traveler and one as a travel agents.

here is my model class user

protected $fillable = [
public function custom_tour_requests()
    return $this->hasMany('App\custom_tour_request', 'traveler_id');        
public function custom_tour_offers()
    return $this->hasManyThrough('App\custom_tour_offer', 'App\custom_tour_request');       

class custom_tour_request

protected $fillable = [
    'title' ,
    'departure' ,
    'destination' ,
    'description' ,
    'start_date' ,
    'budget' ,
    'adult' ,
    'child' ,   
public function user()
    return $this->belongsTo('App\user');
public function custom_tour_offers()
    return $this->hasMany('App\custom_tour_offer', 'custom_tour_request_id');       

class custom_tour_offer

protected $fillable = [
public function custom_tour_request()
    return $this->belongsTo('App\custom_tour_request');
public function user()
    return $this->belongsTo('App\user');

Whenever I tried to insert it return error,

$travelagent = user::find(Auth::user()->id);        
$customtourRequest =   $travelagent->custom_tour_offers()->create($requests->all());

I can't change my database design. I am so confused.

Spycomb Reply to 2015-06-20 23:07:48Z

whats the error? have you re-check the docs and the api for that? maybe you forgot the first() before the create method.



i personally like to do it like custom_tour_offer::create($request->all());

Hkan Reply to 2015-06-21 18:31:02Z

Try this and post the results:

$tourOffers = $travelagent->custom_tour_offers();
$queryBuilder = $tourOffers->getQuery();
$sql = $queryBuilder->getGrammar()->compileInsert($queryBuilder, $requests->all());

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.296419 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO