In the first article of the eCommerce website in Laravel, we have shown you to create database, models and define migration in Laravel. In the second part, we are going to implement controllers and define the application’s routes.
Before proceeding with this section, I request you all to go through with the first part of the article so as to get the small overview and to make your learning journey easier.
Implementing Controllers
In the first article, we have defined controllers for basic operations. They are stored in the app/Http/Controllers directory. At first, we are going to create a UserController. To create the controller, run the following command
1 |
$ php artisan make:controller UserController |
Open the controller file at app/Http/Controllers/UserController.php and write the following content
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<?php namespace App\Http\Controllers; use Auth; use App\User; use Validator; use Illuminate\Http\Request; class UserController extends Controller { public function index() // displays all user with orders { $id=auth()->guard('user')->user()->id; return view()->with(User::find($id)->with(['orders'])->get()); } public function login(Request $request) // authenticates the user { $status = 401; $response = ['error' => 'Unauthorised']; if (Auth::attempt($request->only(['email', 'password']))) { return view('user.dashboard'); } return redirect()->back(); } public function register(Request $request) //create user account { $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 redirect()->back()->withErrors(); } $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('bagisto')->accessToken, ]); } public function show(User $user) // fetch details of users { return response()->json($user); } public function showOrders(User $user) // fetch the orders of the users { return response()->json($user->orders()->with(['product'])->get()); } } |
Next, we create file ProductController and write the below content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
<?php namespace App\Http\Controllers; use App\Product; use Illuminate\Http\Request; class ProductController extends Controller { public function index() // fetch all products { return response()->json(Product::all(),200); } public function store(Request $request) // creates a new product { $product = Product::create([ 'name' => $request->name, 'description' => $request->description, 'quantity' => $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) //upload the product image and fetch the image URL { 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) //Update the 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 Quantity(Request $request, Product $product) //Adds the product quantity { $product->quantity = $product->quantity + $request->get('quantity'); $status = $product->save(); return response()->json([ 'status' => $status, 'message' => $status ? 'Units Added!' : 'Error Adding Product Units' ]); } public function destroy(Product $product) //deletes the product { $status = $product->delete(); return response()->json([ 'status' => $status, 'message' => $status ? 'Product Deleted!' : 'Error Deleting Product' ]); } } |
At last, we create file OrderController and edit as given below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
<?php namespace App\Http\Controllers; use App\Order; use Auth; use Illuminate\Http\Request; class OrderController extends Controller { public function index() // Fetch all Orders { return response()->json(Order::with(['product'])->get(),200); } public function deliverOrder(Order $order) //Set status as Order Delivered { $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) //Creates an Order { $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) //Updates the Order { $status = $order->update( $request->only(['quantity']) ); return response()->json([ 'status' => $status, 'message' => $status ? 'Order Updated!' : 'Error Updating Order' ]); } public function destroy(Order $order) //Deletes the Order { $status = $order->delete(); return response()->json([ 'status' => $status, 'message' => $status ? 'Order Deleted!' : 'Error Deleting Order' ]); } } |
Here we have created the basic controller as per each operation. Now we will be creating application routes to map API requests.
Creating eCommerce Application’s Routes
Laravel application routes are defined in the route files located in the routes directory. Open the file routes/api.php and write the following code snippet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?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::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'); |
After defining the controller and application routes, you can use any of the JavaScript frameworks to build the core front end.
With that, you can create pages for authentication and marketplaces along with the User and Admin dashboard.
For the checkout process, you can use any one of your favorite payment processors which can provide integration into Javascript and PHP framework. After the front end is compiled, run the below command to deliver your application to the Laravel backend.
1 |
$ php artisan serve |
I hope the series might have provided you with the basic understanding of building an eCommerce application in Laravel. Let us know in comments about thoughts and ideas for further improving the article.