DNK
DNK

Reputation: 63

how to fix "Undefined variable: subtask" in Laravel 5.2

need edit My subtask table records, 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);
        //

blade file link to edit button is this, tasks/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
    }

and route is this

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

]);

and edit.blade.php subtasks/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>

but when I click edit button fron blade file got this error massage,

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

how can solve this problem?

Upvotes: 2

Views: 109

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163898

Instead of:

->withTask($subtask)

Do this:

->withSubtask($subtask)

And in the edit view change this:

$task->id

To:

$subtask->task->id

To make the second fix work, you also need to have a properly defined relationship in Subtask model:

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

Upvotes: 1

Related Questions