After many requests from from our users we have updated this tutorial to laravel 5.2 . we’ll be covering folowing laravel 5.2 features Authentication Scaffolding , Authentication Drivers / “Multi-Auth” , & Implicit model binding Too
Here is the link of Demo store created using this tutorial by
Here is the github code of this store
In this tutorial , we’ll code a simple book store example using Laravel. We’ll also cover Laravel’s built-in authentication, named routes, and database seeding. We’ll also elaborate some rapid development methods that come with Laravel such as creating route URLs. Also, we’ll working with a new relation type called belongs to many. We’ll cover pivot tables as well. Our e-commerce application will be a simple book store. This application will have order, administration, and cart features. We will cover the following topics:
- Building an authorization system
- Creating and migrating authors, books, carts, and orders tables
- Creating template files
- Listing books
- Building a shopping cart
- Taking orders
- Listing orders
Building an authorization system
We assume that you have already defined the database credentials in the database.php
file located at config directory
To create our e-commerce application, we need a database. You can create and simply run the following SQL command or basically you can use a database administration interface such as phpMyAdmin:
CREATE DATABASE laravel_store
Creating and migrating the members’ database
Contrary to most of the PHP frameworks, Laravel has a basic and customizable authentication mechanism. The authentication class is very helpful for rapidly developing applications. First, we need a secret key for our application. As we mentioned in previous chapters, the application’s secret key is very important for our application’s security because all the data is hashed salting this key. The artisan can generate this key for us with a single command line:
php artisan key:generate
If no error occurs, you will see a message that tells you the key is generated successfully. After key generation, if you’ve visited your project URL before you face problems with opening your Laravel application, simply clear your browser’s cache and try again. Next, we should edit the authentication class’s configuration file. To use Laravel’s built-in authentication class, we need to edit the configuration file, which is located at config/auth.php
. This file contains several options for the authentication facilities. If you need a change in the table name, and so on, you can make the changes under this file. By default, Laravel comes with a User
model. You can see the file, which is located at app/User.php
. we also need to define which fields are fillable in ourUser
model. Let’s edit User.php
located at app
and add the fillable
array:
<?php use IlluminateAuthUserInterface; use IlluminateAuthRemindersRemindableInterface; class User extends Eloquent implements UserInterface, RemindableInterface { protected $table = 'users'; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = array('password'); //Add to the "fillable" array protected $fillable = array('email', 'password', 'name', 'admin'); /** * Get the unique identifier for the user. * * @return mixed */ public function getAuthIdentifier() { return $this->getKey(); } /** * Get the password for the user. * * @return string */ public function getAuthPassword() { return $this->password; } /** * Get the e-mail address where password reminders are sent. * * @return string */ public function getReminderEmail() { return $this->email; } }
Basically we need four columns for our members. These are:
email
: This is the column for storing a member’s e-mailspassword
: This is the column for storing a member’s passwordname
: This is the column for storing a member’s name and surnameadmin
: This is the column for flagging store admin
Now we need several migration files to create the users
table and add a member to our database. To create a migration file, give a command as follows:
php artisan make:migration create_users_table --table=users --create
Open the migration file, which was created recently and located at database/migrations/
. We need to edit the up()
function, as shown in the following code snippet:
public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('email'); $table->string('password'); $table->string('name'); $table->integer('admin'); $table->timestamps(); }); }
After editing the migration
file, run the migrate
command:
php artisan migrate
Now we need to create a database seeder file to add some users to the database. Database seeding is another highly recommended way to add data to your application database. The database seeder files are located at app/database/seeds
. Let’s create our first seeder file under the UsersTableSeeder.php
directory.
Note
We can create both the seeder file and the seeder class with any name. But it is highly recommended for the seeder file and class name that the table name should follow camel case, for example, TableSeeder
. Following the world-wide programming standards will improve the quality of your code.
The content of UsersTableSeeder.php
should look like the following:
<?php Class UsersTableSeeder extends Seeder { public function run() { DB::table('users')->delete(); User::create(array( 'email' => '[email protected]', 'password' => Hash::make('password'), 'name' => 'John Doe', 'admin'=>0 )); User::create(array( 'email' => '[email protected]', 'password' => Hash::make('adminpassword'), 'name' => 'Jeniffer Taylor', 'admin'=>1 )); } }
To apply seeding, first we need to call the Seeder
class. Let’s open the DatabaseSeeder.php
file located at app/database/seeds
and edit the file, as shown in the following code snippet:
<?php class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Eloquent::unguard(); $this->call('UsersTableSeeder'); $this->command->info('Users table seeded!'); } }
It is very important to securely store your users’ passwords and their critical data. Do not forget that if you change the application key, all the existing hashed records will be unusable because the Hash
class uses the application key as the salting key, when validating and storing given data.
or you can use fakers library to fill your database https://github.com/fzaninotto/Faker
Creating and migrating the authors’ database
We need an Author model for storing the book authors. It will be a very simple structure. Let’s create the Author.php
file under app
and add the following code:
<?php Class Author extends Eloquent { protected $table = 'authors'; protected $fillable = array('name','surname'); }
Now we need several migration files to create the authors
table and add some authors to our database. To create a migration file, give a command as follows:
php artisan make:migration create_authors_table --table=authors --create
Open the migration file that was created recently and located at database/migrations/
. We need to edit the up()
function as follows:
public function up() { Schema::create('authors', function(Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('surname'); $table->timestamps(); }); }
After editing the migration file, run the migrate
command:
php artisan migrate
As you know, the command creates the authors
table and its columns. If no error occurs, check thelaravel_store
database for the authors
table and the columns.
Adding authors to the database
Now we need to create a database seeder file to add some authors to the database. Let’s create our first seeder file under database/seeds/AuthorsTableSeeder.php
.
The content in AuthorsTableSeeder.php
should look like the following:
<?php Class AuthorsTableSeeder extends Seeder { public function run() { DB::table('authors')->delete(); Author::create(array( 'name' => 'Lauren', 'surname'=>'Oliver' )); Author::create(array( 'name' => 'Stephenie', 'surname'=>'Meyer' )); Author::create(array( 'name' => 'Dan', 'surname'=>'Brown' )); } }
To apply seeding, first we need to call the Seeder
class. Let’s open the file DatabaseSeeder.php
located at database/seeds/
and edit the file as shown in the following code snippet:
<?php class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Eloquent::unguard(); $this->call('UsersTableSeeder'); $this->command->info('Users table seeded!'); $this->call('AuthorsTableSeeder'); $this->command->info('Authors table seeded!'); } }
We need to seed our database with the following artisan
command:
php artisan db:seed
Note
When you want to rollback and re-run all migrations, you can use the following command:
php artisan migrate:refresh --seed
Creating and migrating the books database
We need a Book
model to store the author’s books. Let’s create the Book.php
file under app
and add the following code:
<?php Class Book extends Eloquent { protected $table = 'books'; protected $fillable = array('title','isbn','cover','price','author_id'); public function Author(){ return $this->belongsTo('Author'); } }
Let’s explain the role of the author_id
column and the Author()
function. As you know from previous chapters, Eloquent
has several functions for different kinds of database relations. Theauthor_id
will store the ID of the authors. The Author()
function is used to fetch names and surnames of authors from the authors
table.
Adding books to the database
Now we need to create a database seeder file to add some books to the database. Let’s create the first seeder file under app/database/seeds/BooksTableSeeder.php
.
The content in BooksTableSeeder.php
should look like the following:
<?php Class BooksTableSeeder extends Seeder { public function run() { DB::table('books')->delete(); Book::create(array( 'title'=>'Requiem', 'isbn'=>'9780062014535', 'price'=>'13.40', 'cover'=>'requiem.jpg', 'author_id'=>1 )); Book::create(array( 'title'=>'Twilight', 'isbn'=>'9780316015844', 'price'=>'15.40', 'cover'=>'twilight.jpg', 'author_id'=>2 )); Book::create(array( 'title'=>'Deception Point', 'isbn'=>'9780671027384', 'price'=>'16.40', 'cover'=>'deception.jpg', 'author_id'=>3 )); } }
To apply seeding, first we need to call the seeder class. Let’s open the DatabaseSeeder.php
file located at app/database/seeds
and edit the file, as shown in the following code snippet:
<?php class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Eloquent::unguard(); $this->call('UsersTableSeeder'); $this->command->info('Users table seeded!'); $this->call('AuthorsTableSeeder'); $this->command->info('Authors table seeded!'); $this->call('BooksTableSeeder'); $this->command->info('Books table seeded!'); } }
Now, we need to seed our database with the following artisan
command:
php artisan db:seed
Hi, just following this but noticed that:
php artisan make:migartion create_authors_table –table=authors –create
should be:
php artisan make:migration create_authors_table –table=authors –create
(make:migration)
sorry for spelling mistake !
After running php artisan db:seed I was receiving:
[ReflectionException]
Class UsersTableSeeder does not exist
I had to do the following:
composer dump-autoload
php artisan db:seed
After this I received:
[SymfonyComponentDebugExceptionFatalErrorException]
– Not sure how to resolve that error though?
I dont think the dump autoload is needed in 5? Is it referring to a missing class? if so make sure the use appclass is entered on top. I noticed this was missing for alot of things.
I’m seen composer autodump-auto is used in a few places around the web (mostly tuts as I’m learning laravel at the moment). You were right about the class though (just been swatting namespaces this evening) and I was missing the use AppClass from at the top of the file – thanks!
you should using command line to make users seeder :
php artisan make:seeder UsersTableSeeder
then in namespace :
use AppUser;
Its a good tutorial to get started but it had a few typos and omissions. I should have noted them. One thing I would say regarding the last paragraph on passwords is that i think the statement needs to be clarified a bit. it sort of implies that the passwords are also salted with the application key and that users should worry about figuring a way to store passwords, which may lead to additional security issues.
I think it should be noted that the passwords are hashed and salted via bCrypt and persons shoudl read up on how it works but it uses a per password salt not the single application key to salt the passwords. I’m not sure if thats what you meant but it was in the same paragraph.
The application key as I understand it is for other things like encrypting sessions etc. Also while users should know of how the passwords are hashed and salted, they should not be tempted into creating thier own password hashing/encryption algoriithm. bCrypt is solid and if a user wants to make it tougher they can increase the rounds Hash::make(‘thisisthepasswrd’, array(’rounds’ => 15)).
Otherwise thanks for the tut, good way for me to get my feet wet learning Laravel.
ok point noted
There seems to be an inconsistency between the routes file, the user and auth controllers and the blade file when it comes to logins.
“We need to code our login and logout functions in the UserController.php file located at app/controllers.”
Yes, the functions are in the UserController but in the routes file they point to the Auth/AuthController. Also the blades file refer to /user/login but the routes file refer to auth/login.
Also the routes file has this: Route::get(‘auth/login’, ‘AuthAuthController@getLogin’); and this function isnt defined anywhere (unless it is being extended from another class)..
So I think either the routes file should be saying ‘UserController@postLogin… or the login functions should be in the Auth controller. Then the blade file should be pointing to the correct one (either user/login or auth/login)..
i have missed one thing here i am not using built in auth function of laravel
Page 5 Books.php You have : return $this->belongsTo(‘Author’);
It seems to have problems recognizing Author so one may have to do this: ‘AppAuthor’ (or something similar. Also since its using relationships does it need a foreign key? It may need to end up looking like
return $this->belongsTo(‘AppAuthor’,’id’). (Only way I could have gotten it to work).
Cart.php (AppBooks may be needed).
Page 9. refers to the orders but says to save blade file as cart.blade.php
Last major thing I had problem with is the pivot.
It seems that the orders and books table having a many-to-many relationship by default will attempt an insert using the table name book_order. I got a ” Base table or view not found: 1146 Table” error. I did some reading and Laravels documentation gives a clue: ” The role_user table is derived from the alphabetical order of the related model names” So I created a table called book_order and it worked.
So in case anyone else has these issues this may help.
thanks again
may i know , what version of laravel in this tutorial?
laravel 5
5.1?
yes !
Done a tutorial , but after i ran , get too may errors, are you sure this tutorial using laravel 5.1?
please share Errors you got !
FatalErrorException in Model.php line 827:Class ‘Author’ not found
sorry for late reply ! lets solve your problem
TokenMismatchException in VerifyCsrfToken.php line 53:
will fix that ! btw thanks
in laravel5 we need to use make command instead of generate
I fail to see how this is an “e-commerce” tutorial when this “tutorial” doesn’t even cover charging the users card. Did I miss something here?
try out this tut https://dunebook.com/easily-develop-a-ecommerce-website-with-laravel/
Thank you for the link, Deven!
i have an error after seeding class user not found any help noting that there are too many errors in this tut
you need to add, use AppUser; above class at seeder file
hello, how is your AuthAuthController wrote?
UserInterface, RemindableInterface interfaces were removed from Laravel 5.0, how can you still be using them?
Source: https://laravel.com/docs/5.0/upgrade
What happens to the cart.blade.php in last page 4
Done with tutorial, but ‘Add to Cart’ button is not working.(problem in routes.php file)
I just finished this tutorial, and I integrated this e-commerce store with a working Stripe payment system, among some other bug fixes using Laravel 5.2. Who ever is the owner or editor of this website, would you want to upload a part 2 to this tutorial if I uploaded my project to Github using my code?
sure . we are intrested .. thankuuh so much . . shoot an email to hyguyz @outlook.com
There, I sent you an email
yeah. sent in my email [email protected]
thank you so much ,shoot an email [email protected]
please send me at [email protected]
Confused: why doesn’t he used a pivot table called book_order where just the order id and the book id are listed?
Wouldn’t their need to be a pivot table between Cart and Book since just like the relationship/pivot table between Order and Book, a Cart can have multiple books in it and a Book can be in multiple carts?
checkout code of this tutorial https://github.com/hydrogen11/store_ex
I have made a full e-commerce store using the shopping cart method from this tutorial: Here is the website:
http://davidtrushkov.com/store/
and here is the Github code
https://github.com/davidtrushkov/store
thanks , for sharing @davidtrushkov:disqus
Thanks a lot, that was a great help!
Awesome!!!
Thanks for that man
Much Appreciated
Really Good Work .. One of the most valuable comment
There is no administration page to allow the administrator to log in to add products, categories and others?
how to create migration file for the Book?
please upload source code to git.
pls put this command – php artisan make:migration create_books_table –table=books –create
It should be php artisan make:migration create_carts_table –table=carts –create
Hi. If I won’t put the order price on table, just the product and quantity, any idea how can we get the total price from Model ?
please get this project thank you !
[email protected]
Interface ‘IlluminateAuthUserInterface’ not found getting this error after running php artisan db:seed.
We created a similar article for Laravel enthusiasts who want to build a Laravel cart from grounds-up. Check https://therightsw.com/laravel-ecommerce-website-guidelines/
Please I can have the source code of the project?
my email : [email protected]
Its a good tutorial for beginners. but there are some mistakes like you give this “So first, we need a template file under app/controllers/, which is named main_layout.blade.php”. but its not correct to create templates in controllers folder. so document the tutorial according to the standards.
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Class ‘App\Http\Controllers\Book’ not found