Update API - Creating REST API in Laravel(Part V)

Update Api is an api end point for updating records in the database. We are using article as our entity so it will be article update api. In previous article, we have created an store api to store records in database. We have already created database structure, eloquent model, routes, controller functions as well. Now, we will add all necessary logic to update function in controller to create update api.

We have already added update api route in api.php file, you can see this post for reference.

Let's add the logic in the store function of ArticleController like this:

<?php

namespace App\Http\Controllers;

use App\Article;

use Illuminate\Http\Request;
use App\Http\Requests\ArticleRequest;

class ArticleController extends ApiController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  use Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(ArticleRequest $request)
    {
        try{
            $article  =  new Article();
            $article->title = $request->input('title');
            $article->body = $request->input('body');
            $article->save();

            $result['data'] = $article->toArray();
            $result['status'] = true;

        }catch(\Exception $e){
            $result['status'] = false;
            $result['message'] = 'Operation failed due to '. $e->getMessage();
        }
        
        if($result['status']){
            return $this->success($result['data']);
        }else{
            return $this->fail($result['message']);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  use Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ArticleRequest $request, $id)
    {
        try{
            $article  =  Article::find($id);
            if(!$article){
                return $this->notFound('Article not found !');
            }
            $input['title'] = $request->input('title');
            $input['body'] = $request->input('body');

            $article->update($input);

            $result['data'] = $article->toArray();
            $result['status'] = true;

        }catch(\Exception $e){
            $result['status'] = false;
            $result['message'] = 'Operation failed due to '. $e->getMessage();
        }

        if($result['status']){
            return $this->success($result['data']);
        }else{
            return $this->fail($result['message']);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

Now, we have make title and body fillable for the Article model. So add these two columns to fillable array.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = ['title','body'];
}

At first, we have imported the Article model. Then, we will extend our controller from ApiController so that we can send response based on processing of request. Finally, we have added logic to update article in the update function.

We have added try catch block to make sure update of the article. If requested article is not found then we will return not found with HTTP_NOT_FOUND status. For successful update of the article, we will return success with HTTP_OK status. In case of failure, we will return failed response with error message.

Test using Postman(update api)

I'm using ubantu local server. I've hosted my application at localhost:8000. Now, open postman then follow the following steps:

1.Select method type to PATCH

2. Set route to http://localhost:8000/api/articles/8, here 8 is the id of article in my case. It may differ for your case.

3. Add json data in body section of request

Example:

{
   "title":"Greetings",
   "body":"How are you man ?"
}

4. Send the request you will get output like this

{
    "status": "success",
    "status_code": 200,
    "message": "OK",
    "data": {
        "id": 8,
        "title": "Greetings",
        "body": "How are you man ?",
        "created_at": "2019-02-09 11:47:40",
        "updated_at": "2019-02-10 11:01:45"
    }
}
Screenshot

You can find all the details in github: https://github.com/sagautam5/laravel-rest-api

In the next article, we will discuss about api for fetching single article and multiple articles.


share :

Sagar Gautam

A Computer Engineer from Nepal.


Leave your Feedback