Laravel RESTful API

This blog on Laravel restful APIS.

Example we have a database table called tags.

CREATE TABLE `tags` (
`id` int(11) NOT NULL,
`name` varchar(25) DEFAULT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
`status` tinyint(2) DEFAULT NULL
)

Now we need routing to create bread.  BREAD stands for Browse Read Edit Add and delete.

Lets make route for BREAD

Route::get("tags","TagsController@index");
Route::get("tags/{id}","TagsController@show");
Route::post("tags","TagsController@store");
Route::put("tags/{tag}","TagsController@update");
Route::delete("tags/{tag}","TagsController@delete");

Now it’s time to create controller action.

For Browse  :

public function index()
{
     return response()->json(Tag::get(), 200);
}

For Read :

public function show($id)
{
  return response()->json(Tag::find($id), 200);
}

For Add or Store  :

 public function store(Request $request)
 {
        $tag = Tag::create($request->all());
        return response()->json($request->all(), 201);
 }

When you will store or add data, you have to give access to your create operation at your model. So you can give all access in your Tag Model like below.

protected $guarded = ['id'];

For single field access you can use

protected $fillable = ['name'];

For edit :

public function update(Request $request, Tag $tag)
{
     $tag->update($request->all());
     return response()->json($tag, 200);
}

For Delete :

public function delete(Request $request, Tag $tag)
{
        $tag->delete();
        return response()->json(null, 204);
}

That’s it ! Try in post man for test.

Leave a Reply

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