04. Laravel for Frontend developers – storing, updating, and deleting records

Read the previous lesson or watch a screencast version of this post.

In this post, we’ll see how we can create the API endpoints to store, update, and delete food records from the database.

There’s a simple 3 step process you always have to follow when implementing a new endpoint:

  1. Add a new route – based on the action you want to perform, you’ll have to pick the appropriate request type: GET for querying records, POST for storing, PUT for updating, and DELETE for … deleting records 🙂
  2. Implement the corresponding method for the new route
  3. Return a response

Storing a new food item

The first step is to add a new route that will accept a POST request that will then be handled by a store() method on the FoodsController:

Route::post('foods', 'FoodsController@store');

As I said in the previous lesson, Laravel Models allow us to interact with the database without writing any SQL. Instead of writing a full SQL insert statement to store a new food record, all we need to do is to call a create method on the model that receives an array with columns and assigned values. To grab the values from the request, we can use the request($parameter) helper method.

public function store()
{
    return Food::create([
        'name' => request('name'),
        'carbs' => request('carbs'),
        'fats' => request('fats'),
        'proteins' => request('proteins'),
        'calories' => request('calories'),
        'qty' => request('qty'),
        'um' => request('um')
    ]);
}

To check that our new endpoint works, we can use an API client like Postman to submit post requests and see if we are creating any records in the database.

Submitting a post request with Postman

If you have followed this series by the letter, you will probably receive a “mass-assignment” error after submitting the request. The reason behind this is that Laravel offers a protection mechanism against fraudulent filling of the model’s attributes.

Laravel mass-assignment exception

For example, say you have an is_admin column on your users table that determines whether a given user is an admin. You wouldn’t want that column to be changed without your knowledge.

The best thing you can do is always make sure you’re in control of what gets passed into your model – you have to specify each column you want to fill in.

// bad
User::create(request()->all()); // might contain is_admin = true

// good - you're in control of what get's passed to the model
User::create([
   'name' => request('name'),
   'email' => request('email')
])

To disable the mass-assignment protection mechanism, set the $guarded property on the model to an empty array:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Food extends Model
{
    public $table = 'foods';
    protected $guarded = [];
}

Updating an existing food item

Create a route that receives a PUT request and an id parameter, so we know which food item we want to update:

Route::put('foods/{id}', 'FoodsController@update');

Implement the handling, update() method on the FoodsController. First, we need to find the record, update it using the parameters of the request we passed in, and then return it.

public function update($id) 
{
    $food = Food::findOrFail($id);

    $food->update([
        'name' => request('name'),
        'carbs' => request('carbs'),
        'fats' => request('fats'),
        'proteins' => request('proteins'),
        'calories' => request('calories'),
        'qty' => request('qty'),
        'um' => request('um')
    ]);

    return $food;
}

Deleting an existing food item

Same process:

Create a route that receives a DELETE request and an id parameter, so we know which food item we want to delete:

Route::delete('foods/{id}', 'FoodsController@destroy');

Implement the handling, destroy() method on the FoodsController. First, we need to find the record, call the delete() method on it that will remove it from the database, and return a response with a message confirming that we’ve deleted the record.

public function destroy($id)
{
    $food = Food::findOrFail($id);
    $food->delete();

    return response()->json([
        'message' => 'Record deleted'
    ]);
}

Read the previous lesson or watch a screencast version of this post.


Playlist: LFFD

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.