Avoiding PHP PUT/PATCH problem while keeping RESTFUL API style

Avoiding PHP PUT/PATCH problem while keeping RESTFUL API style

One method to avoid a PHP pitfall of PUT and PATCH with _method hacking of POST. This is for Laravel 5. Avoid getting parameters from $request->input() which means getting data from form-data( guessing…) , but to get parameters from $request itself as Object properties.

See below.

    public function update(Request $request, $id)
    {
        if(Article::where('_id', $id)->exists()) {
            $article = Article::find($id);
            $article->title = is_null($request->title) ? $article->title : $request->title;
            $article->article_content = is_null($request->article_content) ? $article->article_content : $request->article_content;
            $article->save();
//            return $article;
            return Article::find($id);
        }
        return response()->json(['code' => Response::HTTP_EXPECTATION_FAILED, 'message' => 'Not a Record found.']);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

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