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 = [
'first_name',
'last_name',
'contact_number',
'photo',
'birthday',
'about',
'email',
'agency',
'logo',
'role',
'status_agency',
'is_admin',
'legal',
'password',
];
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' ,
'end_date',
'budget' ,
'adult' ,
'child' ,
'traveler_id'
];
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 = [
'title',
'departure',
'destination',
'itinerary',
'include',
'exclude',
'start_date',
'end_date',
'price'
];
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.
whats the error? have you re-check the docs and the api for that? maybe you forgot the first() before the create method.
http://laravel.com/docs/5.0/eloquent#querying-relations
http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Relations/HasManyThrough.html
i personally like to do it like custom_tour_offer::create($request->all());
Try this and post the results:
$tourOffers = $travelagent->custom_tour_offers();
$queryBuilder = $tourOffers->getQuery();
$sql = $queryBuilder->getGrammar()->compileInsert($queryBuilder, $requests->all());
dd($sql);