Laravel Change database column when button is clicked

Question

I want to change the status of a task to complete. I have a status_id column in the database and 1 equals complete. I would like the click of the button to change the status_id to 1

My route

Route::patch('/tasks/completed/{Task}', 'TasksController@completedUpdate')->name('completedUpdate');

My button

<form action="{{ route('completedUpdate', $task->id) }}" method="POST">
    {{ csrf_field() }}
    {{ method_field('PATCH') }}
    <button type="submit" class="button is-inverted" style="margin-top: 10px;">Mark Complete</button>
  </form>

My controller

public function completedUpdate(Request $request, $task)
{
    $task->status_id = $request->status_id;

    $task->save;

    return redirect()->back()->with('message', 'task marked complete');
}

the error it gives me is:

Attempt to assign property of non-object

Let me know if any more info is needed


Show source
| laravel   | php   | html   | database   | laravel-5.5   2017-10-04 23:10 3 Answers

Answers to Laravel Change database column when button is clicked ( 3 )

  1. 2017-10-04 23:10

    $task->save; should be $task->save();

    With ->save, it is looking for a property on the model, hence the error message re 'assigning a property'. Whereas ->save() calls the save method on the object.

  2. 2017-10-04 23:10

    In your controller, you're assigning the $task->status_id a value of $request->status_id but you're actually not passing the status_id in your form in your HTML code. You can put a hidden element in your form which is <input name="status_id" value="1" />.

    In the meanwhile, do not forget that $task->save; must be $task->save();

    Good luck!

  3. 2017-10-05 00:10

    You should change:

    public function completedUpdate(Request $request, $task)
    {
        $task->status_id = $request->status_id;
    
        $task->save;
    
        return redirect()->back()->with('message', 'task marked complete');
    }
    

    into:

    public function completedUpdate(Request $request, Task $task)
    {
        $task->status_id = $request->status_id;
    
        $task->save();
    
        return redirect()->back()->with('message', 'task marked complete');
    }
    

    so you need to typehint type of $task variable and use save() method instead of save property.

    Also probably instead of:

    /tasks/completed/{Task}
    

    you should use:

    /tasks/completed/{task}
    

Leave a reply to - Laravel Change database column when button is clicked

◀ Go back