I have created 3 laravel models Organization, User & Contact which have a Laravel HasManyThrough relation.
I have defined all the required relationships for the Models.
I have to update a specific field named 'deletedate' of a contact which belongs to an Organization.
I used the following code:
class ContactsController extends BaseController
{
function __construct()
{
$this->user= User::find(Auth::id());
$this->organization = $this->user->organization;
}
public function update_it()
{
$contact = $this->organization->contact()->find(Input::get('id'));
$contact->deletedate = Carbon\Carbon::now()->toDateTimeString();
print $contact->name;
print $contact->id;
$contact->save();
}
}
In the function function update_it(),
While fetching the data, all the fields of a contact which belongs to that specific Input “id” is extracted except the field “id”. Instead of fetching the id of the Contact, the id of User is bieng fetched.
print $contact->name
This code returns the exact name of the contact that belongs to the input id.
print $contact->id
While this code returns the id of the User.
$contact->save()
This code updates the contact's “deletedate” field whose id is equal to user_id.
Defenition of the three models is given below:
Organization Model :
class Organization extends Eloquent
{
protected $table = 'organizations';
public function contact()
{
return $this->hasManyThrough('Contact', 'User', 'organization_id', 'user_id');
}
}
User Model:
class User extends Eloquent
{
protected $table = 'users';
public function contact()
{
return $this->hasMany('Contact');
}
public function organization()
{
return $this->belongsTo('Organization');
}
}
Contact Model:
class Contact extends Eloquent
{
protected $table = 'contacts';
public function user()
{
return $this->belongsTo('User');
}
}