Web
Analytics
Press "Enter" to skip to content

A Complete Guide to Make an eCommerce Website in Laravel?

Colin Rooney 0

It will not be exaggerating to say that PHP is the backbone of the internet. Because almost 39.9% of the websites, including the WordPress platform’s core, are powered by PHP today. Facebook, which is one of the biggest social media platforms uses it too. Also, open-source platforms like PHP have a great impact in building eCommerce websites, and one such PHP-based framework is Laravel. It is said that Laravel is very beneficial for your e-Commerce application development project.

Laravel & e-commerce – An overview 

Want an open-source PHP framework to create websites or web apps, then Laravel is the best available option for you. It has a shorter learning curve, and it comes with various modern built-in libraries. 

Now you can manage dependencies and packages using the Composer from Laravel. Such packages are very useful in speeding up your Laravel web development project. It also helps you with stuff like API interactions, authentications, debugging, and more. You can get these packages and more resources from sites like Packagist and Packalyst. 

After the launch of Laravel 8 in September 2020, it is armed with advanced and powerful features like job batching, improved rate-limiting, dynamic blade components, Laravel Jetstream, Tailwind pagination views, time testing helpers, model factory classes, and many more.

Laravel eCommerce development tools 

There are a large number of laravel eCommerce packages out there that can help you set up eCommerce functionalities on your laravel e-commerce application very quickly. And some of the most popular laravel tools and packages are mentioned below: 

  • Bagisto — It is a Code-driven & multi-featured Laravel package for e-commerce development. It is completely free & open-source.
  • Aimeos — An online solution package and a Laravel e-commerce tool. Again it’s free & open-source.
  • AvoRed — A modular and customizable PHP shopping cart. Free & open-source.
  • Vanilo — This is an e-commerce framework similar to Magento or Prestashop and is used for Laravel development.
  • GetCandy — An headless Laravel e-commerce API. Free & open-source.

So, what next? There are only three options available while using laravel for eCommerce web development. They are as follow:

  • Picking a Laravel-powered CMS. And adding custom e-commerce to it.
  • Extend your laravel application using an e-commerce package 
  • Develop your e-commerce application right from the scratch.

All of these above-mentioned eCommerce website development tools can offer you the benefits like easy customization, high scalability, detached eCommerce functionalities, and more. 

Creating an e-commerce website using Laravel

Prerequisites

Before we get on with the process make sure you have a working installation of PHP and composer up and running. We will use Sail in this blog for e-commerce web app development. To streamline the eCommerce website development environment and database setup, we will use the laravel 8’s lightweight command-line interface. It will help us interact with Laravel’s default Docker development environment. 

The sail will also help us completely isolate the database from our local environment and quickly set up a development environment for an eCommerce web app. You will also need to get a Docker Desktop to make the interaction between sail and a Docker environment. But if you want then you could always use Homestead from laravel or plug it into a local SQL database. However, Homestead is widely used by Laravel developers as it enables you to get started very quickly. 

1. Creating an e-commerce Laravel development project

Laravel renders a basic command called init to initiate an eCommerce development project. First, make it available by running: composer global require laravel/installer. Then create the project: composer create-project laravel/laravel laravel-project. And cd laravel-project to go into the project’s folder. From now on, all laravel-related commands will run with artisan. Artisan is the command-line interface included with Laravel, which allows the scaffolding of anything in a Laravel project.

2. Create the Sail environment

Laravel Sail comes preinstalled with Laravel 8 projects. And if you want to install them to an existing project then you just need to run the given commands:

composer require laravel/sail –dev

php artisan sail: install

Then, run the command – ./vendor/bin/sail to start your eCommerce development environment. It will include a database and an email server. It will also handle all the store-related emails for you. Also, it is highly recommended that you set a sail alias in your terminal for  ./vendor/bin/sail. If you want to use bash in it then you need to add alias sail=’bash vendor/bin/sail’ in your .bashrc file. 

3. Generating a basic product listing

After reading the setup for our laravel project, it is time to add up the components, we would need a data model and a controller for our laravel web application. We would build them with the help of the below command: 

php artisan make: model -a Ingredient

This will be responsible for the creation of a few files as follow: 

  • A migration, in database/migrations/{date}_create_ingredients_table.php
  • A controller, in app/Http/Controllers/IngredientController.php
  • A model, in app/Models/Ingredient.php
  • A seeder, in database/seeders/IngredientSeeder.php

Now you have to remove all the methods from the controller except the index one. After fetching all the ingredients from the database with the help of Eloquent ORM, the controller returns them as a JSON list. ORM as in object-relational mapper can allow you to write queries in the code language of your choice or in this case, it is PHP. the JSON list created by the controller that uses the Eloquent ORM looks like: 

<?php
namespace App\Http\Controllers;
/**
* Added by the make: model command
* This allows querying the DB for ingredients
*/
use App\Models\Ingredient;
use Illuminate\Http\Request;
/**
* We add this `use` to return a JSON response
*/
use Illuminate\Http\Response;
class IngredientController extends Controller
{
public function index()
{
/**
* `Ingredient::all()` fetch all ingredients
* `->jsonSerialize()` format them as a json list
*/
return response()->json(Ingredient::all()->jsonSerialize());
}
}

All the ingredients will be taken and returned in a JSON format through this method. But from the API endpoint, one thing is there that is missing and it links the controller method to a route or matches the method to a URL. you just need to add the following line of code: Route::get(‘/ingredients’, [IngredientController::class,’index’]); in routes/api.php

This maps GET requests on /API/ingredients to your index method on the IngredientController. To set up the prices dramatically, you can use JSON by having some APIs enabled for it. But if you want to adopt a more traditional approach then you could use MVC instead of APIs and also return a view instead of JSON: view(‘ingredients.list’, [‘ingredients’ => Ingredient::all()]);

Now you have to create a view with the help of the blade templating engine of the PHP Laravel framework. After the controller is ready, we would need to define what kind of ingredient is there in migration files. You can execute the following lines of code for it. 

Schema::create('ingredients', function (Blueprint $table) {

$table->bigIncrements('id');

$table->string('name');

$table->mediumText('description')->nullable();

$table->string('category');

$table->decimal('price_per_gram', 8, 3);

});

Are you wondering about how your database ingredient table should look then this model exactly defines the same? Have a proper look to get an idea. Still, we need to create a database for it. And for that, we need to run the migration with sail artisan migration. This simple command will imply a migration. Executing the required changes to the database, which would be building an ingredient table and adding some relevant roles and columns, would be included in the migration. By now, the controller would also have started working. By fetching at  {{YOUR_APP_PORT}}/api/ingredients, you will get an empty list. 

class IngredientsTableSeeder extends Seeder

{

public function run()

{

DB::table('ingredients')->insert([

[

'name' => 'Quick Oats',

'description' => '100% whole grain oats (quick cooking)',

'category' => 'oats',

'price_per_gram' => 0.007,

],

/* ... many more! ... */

]);

}

}

We would now need to feed initial information in the DB or need to have fake data to play. And for that, we can use the seeders. You should run sail artisan db:seed –class=IngredientSeeder to put that into the database. After this execution, you will get everything in JSON when fetching /api/ingredients. 

4. Using advanced models for custom recipes

If you stop right here then you will have a base for your headless product API selling ingredients. Now, all we need is a way to combine these ingredients into a custom recipe. The advanced Laravel model would enable you to fulfill it. Just add a “Recipe” controller with its model. This model consists of many ingredients. And each one of those ingredients possesses a quality. This can be represented with the following schema: 

Here, the relation table is IngredientRecipe. Using this, you can link many ingredients to many recipes and many recipes to many ingredients. This is known as a many-to-many relationship. A special table will also be allotted to represent each link between the two tables. Here, we can add a quantity that can represent “how much” for every ingredient present in a single recipe. Now we can create new tables with the terminal command PHP artisan make:  migration create_recipes_and_relation. And then we have to edit {date}_create_recipes_and_relation.php so that it consists as mentioned below: 

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreateRecipesAndRelation extends Migration

{

public function up()

{

/**

* This is the main table for a recipe

* created dynamically by a customer on the site

*/

Schema::create('recipes', function (Blueprint $table) {

$table->uuid('id')->primary();

$table->string('name');

$table->string('size');

$table->timestamps();

});

/**

* This is the "relation" table which serves to link

* a recipe to a list of ingredients.

* That one essentially have reference

* to the other tables' ids.

* But also the quantity of each ingredient

*/

Schema::create('ingredient_recipe', function (Blueprint $table) {

$table->bigIncrements('id');

$table->timestamps();

$table->uuid('recipe_id')->index();

$table->bigInteger('ingredient_id')->unsigned()->index();

$table->foreign('recipe_id')->references('id')->on('recipes');

$table->foreign('ingredient_id')->references('id')->on('ingredients');

$table->decimal('quantity', 2, 3);

});

}

public function down()

{

Schema::dropIfExists('ingredient_recipe');

Schema::dropIfExists('recipes');

}

}

We can build a RecipeController using many methods. First, we need to save a method that can store customized recipes in a database. Just add the following code in RecipeController.php

public function save(Request $request)

{

$recipe = new Recipe;

$recipe->name = $request->input('name');

$recipe->size = $request->input('size');

$recipe->save();

$items = array_map(function ($item) use ($recipe) {

return [

'recipe_id' => $recipe->id,

'ingredient_id' => $item['id'],

'quantity' => $item['quantity'],

];

}, $request->input('items'));

IngredientRecipe::insert($items);

$ingredients = Recipe::find($recipe->id)

->ingredients->map(function ($ingredient) {

$ingredient->quantity = $ingredient->pivot->quantity;

return $ingredient;

});

$price = $this->calculatePrice($ingredients, $recipe->size);

return response()

->json([

'id' => $recipe->id,

'name' => 'Recipe ' . $recipe->name . ' (' . $recipe->size . ')',

'url' => '/api/recipe/' . $recipe->id,

'price' => $price,

]);

}

Now, add the following code to register that route 

routes/api.php: Route::post(‘/recipes’, ‘[email protected]’);

This method will not only help you have the recipe but it will also allow the entries with relation to the table it is inserted in. And it depends on both Recipe and Ingredient alike. After returning a JSON of a product definition including ID, name, URL, and price to complete the save method. In the next step, we will have to add a fetch method through with the help of the following code in RecipeController.php: 

public function fetch($id) {

$recipe = Recipe::find($id);

$ingredients = $recipe->ingredients

->map(function($ingredient) {

$ingredient->quantity = $ingredient->pivot->quantity;

return $ingredient;

});

$price = $this->calculatePrice($ingredients, $recipe->size);

return response()

->json([

'id' => $recipe->id,

'name' => 'Recipe '.$recipe->name.' ('.$recipe->size.')',

'url' => '/api/recipe/'.$recipe->id,

'price' => $price,

]);

}

If you call fetch, you can go to the end of the save method and reduce your code. Just make sure of one thing: don’t repeat yourself. Now add the following code to routes/api.php: Route::get(‘/recipe/{id}’, ‘[email protected]’); to get that route registered.And then add the preview method to the controller:

public function preview(Request $request)

{

$items = $request->input('items');

$ingredientIds = array_map(function ($item) {

return $item['id'];

}, $items);

$quantityForId = function($id) use($items) {

for($i = 0; $i < count($items); $i++) {

if($items[$i]['id'] == $id) {

return $items[$i]['quantity'];

}

}

};

$ingredients = Ingredient::whereIn('id', $ingredientIds)

->get()

->map(function($ingredient) use($quantityForId) {

$ingredient->quantity = $quantityForId($ingredient->id);

return $ingredient;

});

$size = $request->input('size');

return response()

->json([

'price' => $this->calculatePrice($ingredients, $size),

]);

}

As a result of it, we will get a gist. After this we need to add Route::post(‘/recipes/preview’, [RecipeController::class, ‘preview’]); to routes/api.php. From the previous endpoint, we have returned to the route for the product’s URL. Now, you can validate the price of a saved price with the help of a crawler. This is very similar to the end of saving and fetching every ingredient of a recipe and its quantity. The controller methods ought to have some impressive uses for Eloquent. For example, the map method allows the e-commerce developers to transform some queried data cleanly and functionally. Then to fetch the ingredients with a recipe, developers need to access the ingredients. 

Add the IngredientRecipe junction table with the following command: php artisan make: model IngredientRecipe. To make Laravel ORM (object-relational mapping) understand the relation schema to add a model. Then we have to make it extend Pivot instead of Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\Pivot;

class IngredientRecipe extends Pivot

{

}

Now eCommerce developers have to create a recipe model with the following command: php artisan make:model Recipe :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Recipe extends Model

{

public function ingredients()

{

return $this->belongsToMany('App\Models\Ingredient')

->using('App\Models\IngredientRecipe')

->withPivot(['quantity']);

}

}

We now have a JSON API that provides:

  • An endpoint to list available ingredients
  • An endpoint to save a Recipe with all of its ingredients quantity
  • An endpoint to retrieve the saved recipe’s price (as expected by a crawler)

Now, Do you have your data? Do you have your logic? If yes, then now we have to move towards linking the API endpoints to eCommerce frontends. 

5. Wiring this all in the frontend

For the frontend development, you can use any good technology framework you like. Here, I’m giving an example of the Vue development framework  to add a barebone vue project with the help of the following command lines: 

  • composer require laravel/ui –dev
  • php artisan ui vue
  • npm install

The above-mentioned commands will create some basic vue.js files in the resources folder. Laravel developers can now compile these files in “watch” mode with the help of laravel sail npm run watch and serve to our root endpoint. 

To query API, we will be using the Axios library. The front end first loads our ingredient list from /api/ingredients. Then let the customer select some of them for a recipe. After that is completed, give the recipe a name, have a price preview using the preview method we created earlier in this post. also, save it all if assuming the method would be used again later for similar purposes. In the code repo linked below, look in the App. vue component at resources/js/components/App.vue. The created method will call our ingredient endpoint.

async created() {

const response = await axios.get("/api/ingredients");

this.allIngredients = response.data;

}

Once that’s done, customers will be able to click a buy button which executes this code:

async buy() {

const payload = {

name: this.name,

size: this.size,

items: this.ingredients.map(x => ({

id: x.id,

quantity: x.quantity,

})),

};

const response = await axios.post('/api/recipes', payload);

const host = window.location.protocol+'//'+window.location.host;

Snipcart.api.cart.items.add({

...response.data,

url: host+response.data.url,

});

It builds the request body expected by POST /api/recipes and will return a product definition that eCommerce developers can use to integrate the cart.

Closing thoughts

Ecommerce developers all over the world are pleased with the functionalities and features of the php laravel framework. Its Eloquent ORM is used to modelize complicated schemas. The artisan command line will streamline the eCommerce website development whereas the sail command line and built-in docker environment will set up an environment for your eCommerce development project. In short, using laravel for building an eCommerce web app will make the development process as seamless as possible. 

Creating an eCommerce website using laravel will enable you to gain complete control over the storage and management of the website data too. You can also add some powerful integrated features like the MVC framework with first-class support for JSON. The latest version of laravel would allow you to maintain migration effortlessly. 

Laravel framework can save you from potential pitfalls and setbacks not to mention the headaches of managing complex and messier processes of eCommerce development. It is also great in the context of documentation and very helpful in the way that it has a large community to provide support to every laravel developer no matter what the project is. The laravel community comes together to solve the problem of one. There is so much that beginner Laravel developers could learn from the community. So, that was the PHP coding on how to make an eCommerce website in laravel for your next project. If you have any more queries or suggestions then please share them with us in the comments section below.

Leave a Reply

Your email address will not be published.