Adi Kurniawan
Adi Kurniawan

Reputation: 91

Laravel 5.3 Database Update From Button Click

So I'm building an app to monitor tasks / jobs. Each job has a status and the default is "1". If it has been finished, the user will click a button, which will change the status to "2", meaning it's done. However, I haven't been successful so far and I will be needing your help.

So far, this is what I have done

The button link:

<p>
{{ link_to('job/detail/' . $job->id, 'Finish Task', ['class' => 'btn btn-primary btn-lg']) }}
</p>

The controller:

public function finish($id)
{
   $job = Job::findOrFail($id);
   $job->update(['status' => '2']);
}

And finally, my route, which I have the biggest doubt. Because I might have two conflicting routes

Route::get('job/detail/{job}', 'JobController@show');
Route::put('job/detail/{job}', 'JobController@finish');

I didn't use any form, and I wanted to do the update right from the button click. Is that possible?

Thanks for the answers

Upvotes: 0

Views: 1229

Answers (2)

Tohid Dadashnezhad
Tohid Dadashnezhad

Reputation: 1938

If you would like to make it more secure you should use PUT method as you did:

Route::put('job/detail/{job}/finished', 'JobController@finish');

/*********/

public function finish(Request $request,Job $job){
  $this->validate($request,[
   'status'=>'required|in:2'
  ]);

  $job->update(['status'=>$request->only('status')]);
}

/*********/

<form action="/job/detail/{{$job->id}}/finished" method="POST">
   {{csrf_field()}}
   <input type="hidden" name="_method" value="PUT"></input>  
   <input type="hidden" name="status" value="2"></input>
   <button type="submit" class="btn btn-primary">Change Staus</button>
</form>

Without using form:

Route::get('job/detail/{job}/finished', 'JobController@finish');

/*********/

public function finish(Job $job){

  $job->update(['status'=>2);

}

/*********/
<a href="/job/detail/{{$job->id}}/finished" class="btn btn-primary">Change Status</a>

As you can see I've added finished at the end of the link because it may has conflict with your other get route.

Upvotes: 1

Ali Rasheed
Ali Rasheed

Reputation: 2817

Try this, try to change the url a bit and this would work. Try and tell

Route::get('job/detail/{job}/action', 'JobController@finish');


public function finish($id)
{
    Job::find($id)->update(['status' => '2']);
}

<p>
 {{ link_to('job/detail/' . $job->id. '/action', 'Finish Task', ['class' => 'btn btn-primary btn-lg']) }}
 </p>

Upvotes: 0

Related Questions