Wednesday, January 30, 2019

What Changes Have Been Made While Implementing Laravel Authentication

What Changes Have Been Made While Implementing Laravel Authentication

Implementation of Laravel authentication is very simple. All you need is to execute
php artisan make:auth, then it generates the authentication functions already.

However, I would like to know what changes have been made in order to modify it and to fit into my own code. There is a way to do so: git version control.

All I have to do is to commit everything before making authentication and show the difference after. It will show the changes have been made.

Let’s start a Laravel project called “Laravel_test”.

Start the test project

> laravel new laravel_test
      :
      :
> cd laravel_test

Start git control

  git init
  git add .
  git commit -m "Initial Commit"

Make Authentication

Now execute the make:auth command.

> php artisan make:auth
Authentication scaffolding generated successfully.

Show the files changed and added:

> git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   routes/web.php

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	app/Http/Controllers/HomeController.php
	resources/views/auth/
	resources/views/home.blade.php
	resources/views/layouts/
  • File changed: routes/web.php
  Auth::routes();
  Route::get('/home', 'HomeController@index')->name('home');
  • Files added:
  1. app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }
}
  1. resources/views/auth/

    resources/views/auth/passwords/email.blade.php
    resources/views/auth/passwords/reset.blade.php
    resources/views/auth/login.blade.php
    resources/views/auth/register.blade.php
    resources/views/auth/verify.blade.php

  2. resources/views/layouts/app.blade.php

  3. resources/views/home.blade.php

Remove the Laravel authentication

The changes havn’t been commited yet at this stage. If we need to go back to the original status (before make:auth), just run the git command:

  1. Revert changes to modified files.
> git reset --hard
HEAD is now at 096f938 Add README.txt

The routes/web.php has been changed to the original status.

  1. Remove all untracked files and directories.
    (-f is force, -d is remove directories)
> git clean -fd 
Removing app/Http/Controllers/HomeController.php
Removing resources/views/auth/
Removing resources/views/home.blade.php
Removing resources/views/layouts/

Wednesday, January 9, 2019

How to Add Constants in Larvel 5

How to Add Constants in Larvel 5

If it needs to add constants in order to be used everywhere in the app, just follows the steps below:

1. Create a file constants.php inside config directory and put your settings in an array:

file : config/constants.php

<?php
  return [
    'PAGINATION' => 5
  ];
?>

2. Then you can get the value by using ‘config helper’ anywhere in your controllers or views in Laravel 5:

echo config('constants.PAGINATION');
//output-> 5

Friday, January 4, 2019

Adding Search Field for The CRUD Web App in Laravel

Adding Search Field for The CRUD Web App in Laravel

Search Box

A search field is a useful function for users to find the information they need. To make a search field toward a web app in Laravel, their are few steps to go:

1. Make a route to the search function.

Firstly, we need to add a route to the search function in the route file (routes/web.php).

Route::post('/products/search', 'ProductController@search')->name('products.search');

This means the URI is /products/search with http method ‘post’ and route the request to the ‘search’ method in the ‘Product’ controller. The route name is ‘products.search’.

2. Make the search method in the controller.

The ‘search’ method in the ‘Product’ controller should be looked like this:

  • Single keyword
    If we have only one keyword, it is much simpler to deal with than the multiple one situation.
public function search(Request $request)
{
  $request->validate([
    'keyword' => 'required'
  ]);
  $keyword = $request->get('keyword');
  //single keyword search - start
  $products = Product::where('prod_name', 'like', '%'.$keyword.'%')
    orWhere('prod_desc', 'like', '%'.$keyword.'%')->get();
  $products = Product::paginate(5); 
  // single keyword search - end
  return view('products.index', compact('products'));      
}
  • Multiple keywords
    What if we have more than one keywords? If so we need to change the ‘single keyword search’ of the code to the following:
  $keywords = explode(' ', $request->get('keyword'));
  $where = '';
  foreach ($keywords as $id => $word) {
    if ($id <> 0) 
      $where = $where.'or ';
    }
  $where = $where."prod_name like '%{$word}%' or prod_desc like '%{$word}%'";  
  }
  $sql = "$where ORDER BY 'prod_id' DESC";
  $products = Product::whereRaw($sql)->get();

3. Make a search field in the menu bar of the index view file.

Lastly, we need to add the following code to the index file in order to show the search box in the main menu bar. The file is
resources/views/products/layout.blade.php in this example.

 <form method="post" action="{{ route('products.search') }}" class="form-inline my-2 my-lg-0">
   @csrf
   <input class="form-control mr-sm-2" type="text" placeholder="Search" 
     aria-label="Search" name="keyword">
   <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>

As usual, a submit form tag is added with http post method. The action to {{ route('products.search' }} is the blade template function to route to the route named ‘products.search’.

Tuesday, January 1, 2019

Seeding Database in Laravel

Seeding Database in Laravel

How to seed the database in Laravel? If we wish to use real data for the seeding, just edit the array $arrayOfSeed in database/seedsDatabaseSeeder.php and put the real data in it.

database/seeds/DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
    	  // 
    $arrayOfSeed = [
      ['id' => 1, 'prod_name' => 'A1000', 'prod_desc' => '26\"x21\" MTB Orange', 'prod_price' => 12000 , 'prod_qty' => 22],  
      ['id' => 2, 'prod_name' => 'A1100', 'prod_desc' => '26\"x19\" MTB Silver', 'prod_price' => 12300 , 'prod_qty' => 21],
      ['id' => 3, 'prod_name' => 'A1200', 'prod_desc' => '26\"x17\" MTB Black', 'prod_price' => 13000 , 'prod_qty' => 5],
      ['id' => 4, 'prod_name' => 'A1300', 'prod_desc' => '26\"x22\" MTB Red', 'prod_price' => 12300 , 'prod_qty' => 8],
      ['id' => 5, 'prod_name' => 'A1400', 'prod_desc' => '26\"x23\" MTB Blue/White', 'prod_price' => 13000 , 'prod_qty' => 6],
      ['id' => 6, 'prod_name' => 'A1500', 'prod_desc' => '26\"x23\" MTB Purple/White', 'prod_price' => 13000 , 'prod_qty' => 12],
      ['id' => 7, 'prod_name' => 'A1600', 'prod_desc' => '26\"x23\" MTB Black/White', 'prod_price' => 13000 , 'prod_qty' => 8],
      ['id' => 8, 'prod_name' => 'A1700', 'prod_desc' => '26\"x23\" MTB Gray/Black', 'prod_price' => 13000 , 'prod_qty' => 4],
      ['id' => 9, 'prod_name' => 'A1800', 'prod_desc' => '26\"x24\" MTB Yellow', 'prod_price' => 13000 , 'prod_qty' => 5],
      ['id' => 10, 'prod_name' => 'A1900', 'prod_desc' => '26\"x24\" MTB Black', 'prod_price' => 13000 , 'prod_qty' => 12],
      ['id' => 11, 'prod_name' => 'A2000', 'prod_desc' => '26\"x21\" MTB lady Orange', 'prod_price' => 12000 , 'prod_qty' => 10],
      ['id' => 12, 'prod_name' => 'A2100', 'prod_desc' => '26\"x19\" MTB lady Silver', 'prod_price' => 12300 , 'prod_qty' => 11]  
    ];
    DB::table('products')->insert($arrayOfSeed);
    }
}

After preparing the DatabaseSeeder.php, run the seeding commend:

$> php artisan db:seed

Done!