Building a Blog With Reactjs And Laravel Controllers

Building a Blog With Reactjs And Laravel Part2: Controllers

In previous part of this tutorial we start building the app database and authentication, in this part we will create the resource controllers that will handle the crud of our application.




As we talking about single page application, the controllers must return a json response so we will utilize using laravel resourceful controllers so we will create a resource controller for each module, laravel supports the resource controllers simply append –resource option after the make controller artisan command like this:


Category Controller

Open app/Http/Controllers/CategoryController.php and update it as follows:



Tags Controller


Posts Controller


In the above code the index method return all posts or posts for specific category. The store() and update() methods creates or updates specific post respectively. For the post tags i use laravel sync() method which used to save many to many relationships by accepting an array of ids in this case tags can be an array like this [1,2,3]. Also for uploading post photo make a writable uploads/ directory inside of public/ directory.


Comments Controller


The comments controller enable us to view and add comments to posts, so in the index() method i made a check if there is post_id parameter passed along with the request then we fetch the approved comments for that post otherwise we list all comments. The store, update and destroy methods are self explanatory.

Users Controller


In the above code the users controller is limited to admin only so i added a simple check to prevent unauthorized users to view or add users by checking for is_admin flag. The is_admin flag is added to users table in previous lesson of this tutorial. I have added a new method profile() which retrieves the profile data for the current authenticated user.

Updating Routes

Let’s open routes/api.php and update it with the following contents:

Now you can experiment with these routes in any restful client, i prefer using postman client and try to register and login then add posts, comments , tags. In the next tutorial we will begin handling the client side using Reactjs.


Continue to part3: Begin Reactjs


Share this: