Cleanest way to save model and relationships

Posted 2 years ago by craigivemy

Hi. I am in the process of building a front end Angular app that consumes the API that I have / am building in Laravel.

I am wondering the best way to take an object sent from the front end to my api, including relationships (as arrays of nested objects) and saving.

Rather than manually typing out something like:

    1:    $task->owner = $request->input('owner');
        2:    $task->client = $request->input('client');
        3:    $task->campaign_id = $request->input('campaign_id');
        4:    $task->title = $request->input('title');
        5:    $task->notes = $request->input('notes');
        6:    $task->viewed = $request->input('viewed');
        7:    $task->priority = $request->input('priority');
        8:    $task->progress = $request->input('progress');
        9:    $task->start_date = $request->input('start_date');
        10: $task->end_date = $request->input('end_date');
        11: $task->departments = $request->input('departments')

I appreciate the fill() method can be used, before save() - but does this handle any relationships?

Owner to task is one to many, so is client to task, whereas department to task is a many to many relationship. What would people recommend doing here if fill() doesn't include relationships (I find it very hard to understand how it possible could) - extract the relationships and handle them separately and use fill() for the single values?

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