Reputation: 1406
I have used built in
resource
method on my routes for a particular controller to generate standard CRUD routes, but I can't figure out how to update a resource. I'm trying to create an API, so I am using App\Http\Resources
, not just models. Here is the code in my controller attempting to update, but it does not work:
public function update(Request $request, Sample $sample)
{
$sample = Sample::where('id', $request->id)->update($request->all());
}
I'm using postman to check my routes, and I'm attempting a put
request with raw updated JSON to app.dev/api/samples/1 but after putting a get
request to same url I can see that values have not changed.
How can I make this update work?
EDIT: Here is my api.php routes file
Route::resource('samples', 'SampleController');
Upvotes: 0
Views: 12400
Reputation: 108
in your header in postman try to input like this, i use x-www-form-urlencoded:
Key Value Description
Accept application/json
Content-Type application/x-www-form-urlencoded
in your body in postman try use x-www-form-urlencoded:
key value
name update
content new content
Upvotes: 4
Reputation: 9389
You need to define column as fillable in the model so that they can be updated later. All you need to do is to add following line in Sample Model.
protected $fillable = [ 'name', 'content'];
If this still don't work, feel free to ask.
Upvotes: 1
Reputation: 3184
If this is a standard Laravel resource route/controller and your endpoint is api/samples/1
then your PATCH/PUT update method should look something like this:
public function update(Request $request, $id)
{
$sample = Sample::find($id);
$sample->update($request->all());
}
If your body is JSON then you will probably need:
$sample->update($request->json()->all());
Upvotes: 0
Reputation: 1136
You can write this. Hopefully this will solve your problem,
public function update(Request $request, Sample $sample)
{
$sample = $sample->update($request->all());
}
Upvotes: 0