Rukmi Patel
Rukmi Patel

Reputation: 2561

Laravel 5.2 + How to save record in DB

While working with laravel 5.2 since last 2 weeks, I have found one new method to store records in DB.

For Instance

 User table 
 id      name
 1       Test 1
 2       Test 2

 Project Table
 id     user_id      name
 1      1            Project 1
 2      2            Project 2

User and Project table are linked in Foreign Key constraint.

To store in Project table, I have used below line of code.

Auth::user()->projects()->save($project);

Can I have similar kind of solution if I want to store record in Task table? Where project_id and user_id are foreign key constraints of project and user table respectively.

Task Table 
id    project_id     user_id      name
1     1              1            test task

Upvotes: 2

Views: 1293

Answers (2)

Filip Koblański
Filip Koblański

Reputation: 10018

If you have already pivot then You can make it in the following ways:

1 while attaching

Auth::user()->projects()->attach([1 => ['name' => $name], 2, 3]);

2 while sync

Auth::user()->projects()->sync([1 => ['name' => $name], 2, 3]);

3 on update pivot

Auth::user()->projects()->updateExistingPivot($projectId, ['name' => $name]);

For read

The pivot data you can access throught a collection of related models - then find a model that interests You and get a pivot special field:

$project = Auth::user()->projects->find($projectId);
return $project->pivot->name;

You can get there but only by the way I show you above.

Upvotes: 1

Styphon
Styphon

Reputation: 10447

Yes, you can do this. All you have to do is create two functions in your Tasks model, one for each relationship:

class Task extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
    public function project()
    {
        return $this->belongsTo('App\Project');
    }
}

When you save the task you just use attach them as you would with one.

$user = User::find(1);
$project = Project::find(1);
$task = Task::create();
$task->user()->attach($user);
$task->project()->attach($project);
$task->save();

Upvotes: 1

Related Questions