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-mails
  • password: This is the column for storing a member’s password
  • name: This is the column for storing a member’s name and surname
  • admin: 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 Hashclass 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.phplocated 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