In the previous chapter, we set up our application’s migrations and models, and installed Laravel Passport for authentication. We also planned what the application will look like. In this chapter, we will implement the controllers and handle all requests to our application.

Prerequisites

To continue with this part, please go through the first part of the series first and make sure you have all the requirements from that part.

Building our controllers

In the first chapter, we already defined our models and their accompanying controllers. These controllers reside in the app/Http/Controllers directory. The User model, however, does not have an accompanying controller, so we are going to create that first. Run the following command:

    $ php artisan make:controller UserController

Now, open the created controller file app/Http/Controllers/UserController.php and replace the contents with the following:

    <?php

    namespace App\Http\Controllers;

    use Auth;
    use App\User;
    use Validator;
    use Illuminate\Http\Request;

    class UserController extends Controller
    {
        public function index()
        {
            return response()->json(User::with(['orders'])->get());
        }

        public function login(Request $request)
        {
            $status = 401;
            $response = ['error' => 'Unauthorised'];

            if (Auth::attempt($request->only(['email', 'password']))) {
                $status = 200;
                $response = [
                    'user' => Auth::user(),
                    'token' => Auth::user()->createToken('bigStore')->accessToken,
                ];
            }

            return response()->json($response, $status);
        }

        public function register(Request $request)
        {
            $validator = Validator::make($request->all(), [
                'name' => 'required|max:50',
                'email' => 'required|email',
                'password' => 'required|min:6',
                'c_password' => 'required|same:password',
            ]);

            if ($validator->fails()) {
                return response()->json(['error' => $validator->errors()], 401);
            }

            $data = $request->only(['name', 'email', 'password']);
            $data['password'] = bcrypt($data['password']);

            $user = User::create($data);
            $user->is_admin = 0;

            return response()->json([
                'user' => $user,
                'token' => $user->createToken('bigStore')->accessToken,
            ]);
        }

        public function show(User $user)
        {
            return response()->json($user);
        }

        public function showOrders(User $user)
        {
            return response()->json($user->orders()->with(['product'])->get());
        }

    }

Above we defined some class methods:

  1. index() – returns all users with their orders.
  2. login() – authenticates a user and generates an access token for that user. The createToken method is one of the methods Laravel Passport adds to our user model.
  3. register() – creates a user account, authenticates it and generates an access token for it.
  4. show() – gets the details of a user and returns them.
  5. showOrders() – gets all the orders of a user and returns them.

We used Laravel’s Route-Model Binding to automatically inject our model instance into the controller. The only caveat is that the variable name used for the binding has to be the same as the one defined in the route as well.

Next, open the app/Http/Controllers/ProductController.php file and replace the contents with the following:

    <?php

    namespace App\Http\Controllers;

    use App\Product;
    use Illuminate\Http\Request;

    class ProductController extends Controller
    {
        public function index()
        {
            return response()->json(Product::all(),200);
        }

        public function store(Request $request)
        {
            $product = Product::create([
                'name' => $request->name,
                'description' => $request->description,
                'units' => $request->units,
                'price' => $request->price,
                'image' => $request->image
            ]);

            return response()->json([
                'status' => (bool) $product,
                'data'   => $product,
                'message' => $product ? 'Product Created!' : 'Error Creating Product'
            ]);
        }

        public function show(Product $product)
        {
            return response()->json($product,200); 
        }

        public function uploadFile(Request $request)
        {
            if($request->hasFile('image')){
                $name = time()."_".$request->file('image')->getClientOriginalName();
                $request->file('image')->move(public_path('images'), $name);
            }
            return response()->json(asset("images/$name"),201);
        }

        public function update(Request $request, Product $product)
        {
            $status = $product->update(
                $request->only(['name', 'description', 'units', 'price', 'image'])
            );

            return response()->json([
                'status' => $status,
                'message' => $status ? 'Product Updated!' : 'Error Updating Product'
            ]);
        }

        public function updateUnits(Request $request, Product $product)
        {
            $product->units = $product->units + $request->get('units');
            $status = $product->save();

            return response()->json([
                'status' => $status,
                'message' => $status ? 'Units Added!' : 'Error Adding Product Units'
            ]);
        }

        public function destroy(Product $product)
        {
            $status = $product->delete();

            return response()->json([
                'status' => $status,
                'message' => $status ? 'Product Deleted!' : 'Error Deleting Product'
            ]);
        }
    }

In the ProductController above we defined seven methods:

  1. index() – fetches and returns all the product records.
  2. store() – creates a product record.
  3. show() – fetches and returns a single product.
  4. uploadFile() – uploads the image for a product we created and returns the url for the product.
  5. update() – updates the product record.
  6. updateUnits() – adds new units to a product.
  7. delete() – deletes a product.

Next, open the app/Http/Controllers/OrderController.php file and replace the content with the following:

    <?php

    namespace App\Http\Controllers;

    use App\Order;
    use Auth;
    use Illuminate\Http\Request;

    class OrderController extends Controller
    {
        public function index()
        {
            return response()->json(Order::with(['product'])->get(),200);
        }

        public function deliverOrder(Order $order)
        {
            $order->is_delivered = true;
            $status = $order->save();

            return response()->json([
                'status'    => $status,
                'data'      => $order,
                'message'   => $status ? 'Order Delivered!' : 'Error Delivering Order'
            ]);
        }

        public function store(Request $request)
        {
            $order = Order::create([
                'product_id' => $request->product_id,
                'user_id' => Auth::id(),
                'quantity' => $request->quantity,
                'address' => $request->address
            ]);

            return response()->json([
                'status' => (bool) $order,
                'data'   => $order,
                'message' => $order ? 'Order Created!' : 'Error Creating Order'
            ]);
        }

        public function show(Order $order)
        {
            return response()->json($order,200);
        }

        public function update(Request $request, Order $order)
        {
            $status = $order->update(
                $request->only(['quantity'])
            );

            return response()->json([
                'status' => $status,
                'message' => $status ? 'Order Updated!' : 'Error Updating Order'
            ]);
        }

        public function destroy(Order $order)
        {
            $status = $order->delete();

            return response()->json([
                'status' => $status,
                'message' => $status ? 'Order Deleted!' : 'Error Deleting Order'
            ]);
        }
    }

In the OrderController above we have six methods:

  1. index() – fetches and returns all the orders.
  2. deliverOrder() – marks an order as delivered.
  3. store() – creates an order.
  4. show() – fetches and returns a single order.
  5. update() – updates the order.
  6. destroy() – deletes an order.

That’s it for our controllers. We have created the controller according to the specifications we laid out in the first part. Next thing we need to do is define our API routes.

Defining our application’s routes

Now that we have fully defined all the requests we would like to make to our application, let’s expose the APIs for making these requests. Open routes/api.php file and replace the content with the following:

    <?php

    use Illuminate\Http\Request;

    Route::post('login', 'UserController@login');
    Route::post('register', 'UserController@register');
    Route::get('/products', 'ProductController@index');
    Route::post('/upload-file', 'ProductController@uploadFile');
    Route::get('/products/{product}', 'ProductController@show');

    Route::group(['middleware' => 'auth:api'], function(){
        Route::get('/users','UserController@index');
        Route::get('users/{user}','UserController@show');
        Route::patch('users/{user}','UserController@update');
        Route::get('users/{user}/orders','UserController@showOrders');
        Route::patch('products/{product}/units/add','ProductController@updateUnits');
        Route::patch('orders/{order}/deliver','OrderController@deliverOrder');
        Route::resource('/orders', 'OrderController');
        Route::resource('/products', 'ProductController')->except(['index','show']);
    });

Putting our route definitions in the routes/api.php file will tell Laravel they are API routes so Laravel will prefix the routes with a /api in the URL to differentiate them from web routes.

Adding the auth:api middleware ensures any calls to the routes in that group must be authenticated.

A thing to note is, using the resource method on the Route class helps us create some additional routes under the hood without us having to create them manually. Read about resource controllers and routes here.

💡 To see the full route list, run the following command: $ php artisan route:list

Laravel ecommerce route list

Since we will build the frontend of this application in Vue, we need to define the web routes for it. Open the routes/web.php file and replace the contents with the following:

    <?php

    Route::get('/{any}', function(){
            return view('landing');
    })->where('any', '.*');

This will route every web request to a single entry point, which will be the entry for your Vue application.

Setting up Vue for the frontend

Vue is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable – vuejs.org

Laravel comes with Vue bundled out of the box, so all we need to do to get Vue is to install the node packages. Run the following command:

    $ npm install 

Next, we will need VueRouter to handle the routing between the different components of our Vue application. To install VueRouter run the command below:

    $ npm install vue-router

Next, let’s make the landing view file, which would mount our Vue application. Create the file resources/views/landing.blade.php and add the following code:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{csrf_token()}}">
        <title>Big Store</title>
        <link href=" {{ mix('css/app.css') }}" rel="stylesheet">
    </head>
    <body>
        <div id="app">
            <app></app>
        </div>
        <script src="{{ mix('js/bootstrap.js') }}"></script>
        <script src="{{ mix('js/app.js') }}"></script>
    </body>
    </html>

In the code above, we have the HTML for our application. If you look closely, you can see the app tag. This will be the entry point to our Vue application and where the components will be loaded.

Since we will use app.js to set up our VueRouter, we still need to have Bootstrap and Axios compiled. The import for Bootstrap and Axios is in the bootstrap.js file so we need to compile that.

Edit the webpack.mix.js file so it compiles all assets:

    [...]

    mix.js('resources/assets/js/app.js', 'public/js')
       .js('resources/assets/js/bootstrap.js', 'public/js')
       .sass('resources/assets/sass/app.scss', 'public/css');

💡the webpack.mix.js file holds the configuration files for laravel-mix, which provides a wrapper around Webpack. It lets us take advantage of Webpack’s amazing asset compilation abilities without having to write Webpack configurations by ourselves. You can learn more about Webpack here.

Set up the homepage for the Vue application. Create a new file, resources/assets/js/views/Home.vue, and add the following code to the file:

    <template>
        <div>
            <div class="container-fluid hero-section d-flex align-content-center justify-content-center flex-wrap ml-auto">
                <h2 class="title">Welcome to the bigStore</h2>
            </div>
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <div class="row">
                            <div class="col-md-4 product-box" v-for="(product,index) in products" @key="index">
                                <router-link :to="{ path: '/products/'+product.id}">
                                    <img :src="product.image" :alt="product.name">
                                    <h5><span v-html="product.name"></span>
                                        <span class="small-text text-muted float-right">$ {{product.price}}</span>
                                    </h5>
                                    <button class="col-md-4 btn btn-sm btn-primary float-right">Buy Now</button>
                                </router-link>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>

    <script>
        export default {
            data(){
                return {
                    products : []
                }
            },
            mounted(){
                axios.get("api/products/").then(response => this.products = response.data)      
            }
        }
    </script>

The code above within the opening and closing template tag we have the HTML of our Vue component. In there we loop through the contents of products and for each product we display the image, name, id, price and units available. We use the v-html attribute to render raw HTML, which makes it easy for us to use special characters in the product name.

Within the script tag, we defined the data(), which holds all the variables we can use in our template. We also defined the mounted() method, which is called after our component is loaded. In this mounted method, we load our products from the API then set the products variable so that our template would be updated with API data.

In the same file, append the code below to the bottom:

    <style scoped>
    .small-text {
        font-size: 14px;
    }
    .product-box {
        border: 1px solid #cccccc;
        padding: 10px 15px;
    }
    .hero-section {
        height: 30vh;
        background: #ababab;
        align-items: center;
        margin-bottom: 20px;
        margin-top: -20px;
    }
    .title {
        font-size: 60px;
        color: #ffffff;
    }
    </style>

In the code above, we have defined the style to use with the welcome component.

According to the Vue documentation:

When a <style> tag has the scoped attribute, its CSS will apply to elements of the current component only. This is similar to the style encapsulation found in the Shadow DOM. It comes with some caveats but doesn’t require any polyfills.

Next create another file, resources/assets/js/views/App.vue. This will be the application container where all other components will be loaded. In this file, add the following code:

    <template>
        <div>
            <nav class="navbar navbar-expand-md navbar-light navbar-laravel">
                <div class="container">
                    <router-link :to="{name: 'home'}" class="navbar-brand">Big Store</router-link>
                    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                        <!-- Left Side Of Navbar -->
                        <ul class="navbar-nav mr-auto"></ul>
                        <!-- Right Side Of Navbar -->
                        <ul class="navbar-nav ml-auto">
                            <router-link :to="{ name: 'login' }" class="nav-link" v-if="!isLoggedIn">Login</router-link>
                            <router-link :to="{ name: 'register' }" class="nav-link" v-if="!isLoggedIn">Register</router-link>
                            <span v-if="isLoggedIn">
                                <router-link :to="{ name: 'userboard' }" class="nav-link" v-if="user_type == 0"> Hi, {{name}}</router-link>
                                <router-link :to="{ name: 'admin' }" class="nav-link" v-if="user_type == 1"> Hi, {{name}}</router-link>
                            </span>
                            <li class="nav-link" v-if="isLoggedIn" @click="logout"> Logout</li>
                        </ul>
                    </div>
                </div>
            </nav>
            <main class="py-4">
                <router-view @loggedIn="change"></router-view>
            </main>
        </div>
    </template>

In the Vue template above we used some Vue specific tags like router-link, which helps us generate links for routing to pages defined in our router. We also have the router-view, which is where all the child component pages will be loaded.

Next below the closing template tag, add the following code:

    <script>
    export default {
        data() {
            return {
                name: null,
                user_type: 0,
                isLoggedIn: localStorage.getItem('bigStore.jwt') != null
            }
        },
        mounted() {
            this.setDefaults()
        },
        methods : {
            setDefaults() {
                if (this.isLoggedIn) {
                    let user = JSON.parse(localStorage.getItem('bigStore.user'))
                    this.name = user.name
                    this.user_type = user.is_admin
                }
            },
            change() {
                this.isLoggedIn = localStorage.getItem('bigStore.jwt') != null
                this.setDefaults()
            },
            logout(){
                localStorage.removeItem('bigStore.jwt')
                localStorage.removeItem('bigStore.user')
                this.change()
                this.$router.push('/')
            }
        }
    }
    </script>

In the script definition we have the methods property and in there we have three methods defined:

  1. setDefaults() – sets the name of the user when the user is logged in as well as the type of user logged in.
  2. change()– checks the current login status anytime it is called and calls the setDefaults method.
  3. logout() – logs the user out of the application and routes the user to the homepage.

In our router-view component, we listen for an event loggedIn which calls the change method. This event is fired by our component anytime we log in. It is a way of telling the App component to update itself when a user logs in.

Next create the following files in the resources/assets/js/views directory:

  • Admin.vue
  • Checkout.vue
  • Confirmation.vue
  • Login.vue
  • Register.vue
  • SingleProduct.vue
  • UserBoard.vue

These files would hold all the pages bigStore would have. They need to be created prior to setting up VueRouter, so that it wont throw an error.

To set up the routing for our Vue single page app, open your resources/assets/js/app.js file and replace the contents with the following code:

    import Vue from 'vue'
    import VueRouter from 'vue-router'

    Vue.use(VueRouter)

    import App from './views/App'
    import Home from './views/Home'
    import Login from './views/Login'
    import Register from './views/Register'
    import SingleProduct from './views/SingleProduct'
    import Checkout from './views/Checkout'
    import Confirmation from './views/Confirmation'
    import UserBoard from './views/UserBoard'
    import Admin from './views/Admin'

    const router = new VueRouter({
        mode: 'history',
        routes: [
            {
                path: '/',
                name: 'home',
                component: Home
            },
            {
                path: '/login',
                name: 'login',
                component: Login
            },
            {
                path: '/register',
                name: 'register',
                component: Register
            },
            {
                path: '/products/:id',
                name: 'single-products',
                component: SingleProduct
            },
            {
                path: '/confirmation',
                name: 'confirmation',
                component: Confirmation
            },
            {
                path: '/checkout',
                name: 'checkout',
                component: Checkout,
                props: (route) => ({ pid: route.query.pid })
            },
            {
                path: '/dashboard',
                name: 'userboard',
                component: UserBoard,
                meta: {
                    requiresAuth: true,
                    is_user: true
                }
            },
            {
                path: '/admin/:page',
                name: 'admin-pages',
                component: Admin,
                meta: {
                    requiresAuth: true,
                    is_admin: true
                }
            },
            {
                path: '/admin',
                name: 'admin',
                component: Admin,
                meta: {
                    requiresAuth: true,
                    is_admin: true
                }
            },
        ],
    })

    router.beforeEach((to, from, next) => {
        if (to.matched.some(record => record.meta.requiresAuth)) {
            if (localStorage.getItem('bigStore.jwt') == null) {
                next({
                    path: '/login',
                    params: { nextUrl: to.fullPath }
                })
            } else {
                let user = JSON.parse(localStorage.getItem('bigStore.user'))
                if (to.matched.some(record => record.meta.is_admin)) {
                    if (user.is_admin == 1) {
                        next()
                    }
                    else {
                        next({ name: 'userboard' })
                    }
                }
                else if (to.matched.some(record => record.meta.is_user)) {
                    if (user.is_admin == 0) {
                        next()
                    }
                    else {
                        next({ name: 'admin' })
                    }
                }
                next()
            }
        } else {
            next()
        }
    })

Above, we have imported the VueRouter and we added it to our Vue application. We defined routes for our application and then registered it to the Vue instance so it is available to all Vue components.

Each of the route objects has a name, which we will use to identify and invoke that route. It also has a path, which you can visit directly in your browser. Lastly it has a component, which is mounted when you visit the route.

On some routes, we defined meta, which contains variables we would like to check when we access the route. In our case, we are checking if the route requires authentication and if it is restricted to administrators or regular users only.

We set up the beforeEach middleware on the router that checks each route before going to it. The method takes these variables:

  1. to – the route you want to move to.
  2. from – the current route you are moving away from.
  3. next – the method that finally moves to a defined route. When called without a route passed, it continues the navigation. If given a route, it goes to that route.

We use beforeEach to check the routes that require authentication before you can access them. For those routes, we check if the user is authenticated. If the user isn’t, we send them to the login page. If the user is authenticated, we check if the route is restricted to admin users or regular users. We redirect each user to the right place based on which access level they have.

Now add the following lines to the end of the app.js file

    const app = new Vue({
        el: '#app',
        components: { App },
        router,
    });

This instantiates the Vue application. In this global instance, we mount the App component only because the VueRouter needs it to switch between all the other components.

Now, we are ready to start making the other views for our application.

Conclusion

In this part we implemented the controller logic that handles all the requests to our application and defined all the routes the application will use. We also set up Vue and VueRouter to prepare our application for building the core frontend.

In the next chapter of this guide, we are going to build the core frontend of the application and consume the APIs. See you in the next part.