2 months ago

Clean way to save multiple relathionships on one store call

Posted 2 months ago by Sidirgot

Hello everyone, i am building a bug-tracking application and i choose to go with a simple role field under my users table.

The system will have User Types based on their role, manager / tester and developer.

This is the User model

public function projects()
    return $this->hasMany(Project::class, 'manager_id');

public function testerProjects()
    return $this->hasMany(Project::class, 'tester_id');

public function developerProjects()
    return $this->hasMany(Project::class, 'developer_id');

and this is the projects model

protected $fillable = [
    'title', 'description', 'priority', 'screenshot', 'tester_id', 'developer_id'

public function tester()
    return $this->belongsTo(User::class, 'tester_id');

public function developer()
    return $this->belongsTo(User::class, 'developer_id');

public function manager()
    return $this->belongsTo(User::class, 'manager_id');

Now when a manager goes to store the project he needs to assign a tester and a developer to the project, so here is my Projects Controller store method

public function store(ProjectCreateRequest $request)
    $data = $request->validated();
    $tester = User::find($data['tester_id']);
    $developer = User::find($data['developer_id']);     
    $project =  auth()->user()->projects()->make($data);


    return redirect()->route('projects.index');

I cant decide if the best approach would be to create a function in my User or Project Model and handle all this logic there or go with some other approach.

Any suggestion is appreciated.

Please sign in or create an account to participate in this conversation.