Sunday, March 5, 2017

Laravel 5.x save two models with relationship in one form

I studied the Laravel Intermediate Task tutorial and now I want to create a more complicated app based from it.

I am creating a daily log app to study model dependencies. I have three models: User, DayLog and Task.

  • Users have many DayLogs.
  • DayLogs can have many Tasks (optional).
  • Users and DayLog's relationship and CRUD are working OK which were directly lifted from the tutorial.

Now I want to save a DayLog with a Task which I have a difficulty in achieving.

Here are my models indicating the relationship discussed before:

// User.php
public function dayLogs()
{
    return $this->hasMany(DayLog::class);
}

// DayLog.php
public function user()
{
    return $this->belongsTo(User::class);
}
public function task()
{
    return $this->hasMany(Task::class);
}

// Task.php
public function dayLog()
{
    return $this->belongsTo(DayLog::class);
}

Currently I am developing in the back end. I am trying to associate a Task to this DayLog being saved:

// DayLogController.php
public function create(Request $request)
{
    $this->validate($request, [
        'daylog_name' => 'required|max:255',
    ]);

    // Create dummy Task
    $task = new Task();
    $task->name = "My new task ".date('Ymd');

    // Save Task to the current DayLog - NOK
    $request->daylog()->tasks()->create([
        'task_name' => $task->name,
    ]);

    // Save DayLog to User - OK
    $request->user()->daylogs()->create([
        'name' => $request->daylog_name,
    ]);

    return redirect('/daylogs');
}

This shows an error:

BadMethodCallException in Macroable.php line 74:

Method daylog does not exist.

I do not understand why user() is in $request while daylog() is not.

Basically I would like to successfully save the inline Task as a part of the DayLog inside the method above.

I hope you can help me with this.



via Saggy Manatee And Swan Folk

Advertisement