如何修复Laravel 5.2中的“Undefined variable:subtask”

时间:2017-12-26 13:12:07

标签: php laravel laravel-5 controller laravel-blade

需要编辑我的子任务表记录,SubtaskController

public function edit($projectId,$taskId,$subtaskId)
    {
        $subtask = Subtask::where('project_id', $projectId)
                      ->where('task_id', $taskId)
                      ->where('id', $subtaskId)
                      ->first();
        return view('subtasks.edit')->withTask($subtask)->with('projectId', $projectId)->with('id',$subtaskId);
        //

刀片文件链接到编辑按钮就是这个, 任务/ index.blade.php

@foreach ($task->subtasks as $subtask)
    <ul>
    <li>
  <div>
    <div class="pull-right icons-align">

            <a href="/projects/{{ $project->id }}/tasks/{{ $task->id }}/subtasks/{{$subtask->id}}/edit" class="editInline"><i class="glyphicon glyphicon-pencil"></i></a>
          <a href="/projects/{{ $project->id }}/tasks/{{ $task->id }}/delete" class="editInline" onclick="return confirm('Are you sure to want to delete this record?')"><i class="glyphicon glyphicon-trash"></i></a>
        </div>
        {{ $subtask->subtask_name }}
        </div>

    @endforeach
    }

和路线就是这个

Route::get('projects/{projects}/tasks/{tasks}/subtasks/{subtasks}/edit', [
    'uses' => '\App\Http\Controllers\SubtasksController@edit',

]);

和edit.blade.php 子任务/ edit.blade.php

<div class="col-lg-6">
        <form class="form-vertical" role="form" method="post" action="{{ url('projects/' .$projectId .'/tasks/' . $task->id.'/subtasks/'.$subtask->id) }}"> //this is line 9
            <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                <input type="text" name="task_name" class="form-control" id="name" value="{!! $subtask->subtask_name ?: '' !!}">
                @if ($errors->has('name'))
                    <span class="help-block">{{ $errors->first('name') }}</span>
                @endif
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-info">Update Subtask</button>
            </div>
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            {!! method_field('PUT') !!}
        </form>

但是当我点击编辑按钮fron刀片文件时得到了这个错误按摩,

ErrorException in 9b021095a9def87aed61575bb51efc07798e08da.php line 9: Undefined variable: subtask (View: C:\Users\dnk\Desktop\ddd\resources\views\subtasks\edit.blade.php)

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

而不是:

->withTask($subtask)

这样做:

->withSubtask($subtask)

edit视图中更改此内容:

$task->id

要:

$subtask->task->id

要使第二个修复工作正常,您还需要在Subtask模型中建立正确定义的关系:

public function task()
{
    return $this->belongsTo(Task::class);
}