Monday, November 4, 2019

Laravel : Auth routes 8 Things You Can Customize in Laravel Registration


1. Disable Registration

What if your app has pre-registered users, or they are created by administrator, and there’s no public registration?
Since Laravel 5.7, All you need to do is add a parameter in routes/web.php:
Auth::routes(['register' => false]);
Then you won’t see Register link in top-right corner, and the route /register will show 404 page.

2. Enable Email Verification

Another new feature of Laravel 5.7 is email verification, with database field users.email_verified_at. By default, it is disabled, but all the necessary fields and routes are generated, just hidden.
To enable this function, just pass a parameter in routes/web.php:
Auth::routes(['verify' => true]);
Also, make sure to run php artisan make:auth so it would generate necessary views for users to see after they click verification links.
Finally, if you need some routes available only to verified users, use verified Middleware:
Route::get('profile', function () {
    // Only verified users may enter...
})->middleware('verified');

3. Disable Reset Password

By default, php artisan make:auth command generates the Bootstrap login/register pages, along with one for resetting the forgotten password.
But if you want to disable that feature, and have some other mechanism to recover passwords, there’s another parameter in the routes/web.php:
Auth::routes(['reset' => false]);
Notice: you can combine this with the previous tips about registration and verification, and have this in your routes/web.php:
Auth::routes([
  'register' => false,
  'verify' => true,
  'reset' => false
]);

The underneath actual routes are listed in one method in vendor/laravel/framework/src/Illuminate/Routing/Router.php:
public function auth(array $options = [])
{
    // Authentication Routes...
    $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
    $this->post('login', 'Auth\LoginController@login');
    $this->post('logout', 'Auth\LoginController@logout')->name('logout');

    // Registration Routes...
    if ($options['register'] ?? true) {
        $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
        $this->post('register', 'Auth\RegisterController@register');
    }

    // Password Reset Routes...
    if ($options['reset'] ?? true) {
        $this->resetPassword();
    }

    // Email Verification Routes...
    if ($options['verify'] ?? false) {
        $this->emailVerification();
    }
}

4. Redirect After Registration

By default, new registered users are redirected to URL /home. Perhaps, you want to change it, it’s done in a file app/Http/Controllers/Auth/RegisterController.php:
class RegisterController extends Controller
{
    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';
Just change this one parameter, and that’s it.
But what if you have more complicated logic than just one static URL? For example, you want to register to different URLs based on the role of new user. Then you can create a separate method in the same class RegisterController, with name redirectTo():
protected function redirectTo()
{
    if (auth()->user()->role_id == 1) {
        return '/admin';
    }
    return '/home';
}
The method behavior will override $redirectTo property value, even if the value is present.

5. Change Field Validation Rules

Default Auth has four fields:
  • name
  • email
  • password
  • confirm password
All of them are required, and these validation rules are specified in the same app/Http/Controllers/Auth/RegisterController.php:
protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:6', 'confirmed'],
    ]);
}
So if you want to change any of these, like adding more complicated password requirements than just 6 symbols minimum, just edit this validator() method.

6. Disable Auto-Login after Registration

Another default behavior that you may want to change is auto-login immediately after the registration form. You may want to redirect your user to a separate “success” page and expect them to log in manually later.
To do that, you need to override register() method of a trait RegistersUsers.
The controller we discussed above, RegisterController, uses this important Trait:
class RegisterController extends Controller
{
    use RegistersUsers;
    // ... all other code of controller
This trait performs all the “dirty work” of registration. It is part of the core framework, located in vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php:
trait RegistersUsers
{
    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
                        ?: redirect($this->redirectPath());
    }

    // ... A few other methods

}
To disable auto-login, you need to delete this particular line:
$this->guard()->login($user);
But you can’t edit directly Laravel core, or any part of what’s inside /vendor. What you can do is override the same method and put it in your RegisterController, like this:
namespace App\Http\Controllers\Auth;

// DON'T FORGET TO ADD THESE TWO!
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{

    // ... Other methods

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

}
Finally, take care of redirectTo parameter or method, as shown in previous tip, so your registered user would land on a correct page.

7. Adding More Fields to Registration Form

The most typical example of this would be adding a surname field, in addition to default name. There are a few steps you need to do here:

Step 1. Add field to the database.

Just add this line to some migration file: $table->string(‘surname’);
Choose to edit existing default migration file, or create a new one with php artisan make:migration add_surname_to_users_table.

Step 2. Add field as fillable to User model.

By default, app/User.php has this:
protected $fillable = [
    'name', 'email', 'password',
];
So you need to add your new ‘surname’ into that array.

Step 3. Add the field to View form.

You need to edit resources/views/auth/register.blade.php file and add another field, probably copy-paste all the code for name field and change some parts of it.
<div class="form-group row">
    <label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>

    <div class="col-md-6">
        <input id="name" type="text" class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" value="{{ old('name') }}" required autofocus>

        @if ($errors->has('name'))
            <span class="invalid-feedback" role="alert">
                <strong>{{ $errors->first('name') }}</strong>
            </span>
        @endif
    </div>
</div>

Step 4. Modify create() method.

Here’s how default method looks in RegisterController:
protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}
Guess what, you just need to add another line related to surname, so final result is this:
protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'surname' => $data['surname'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}

8. Login with Username instead of Email

By default, email is the most important field for user, it is used as a unique identifier and is part of the credentials. But what if, in your case, email is just an informational field, and actual login credential is another one, like username?
First, take care of adding that field into the database/model/views, like discussed in previous tip.
Next, you need to take a look at app/Http/Controllers/Auth/LoginController, specifically one trait:
class LoginController extends Controller
{
    use AuthenticatesUsers;
    // ... All other code
If you get deeper into that /vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php trait, you will see one method:
/**
 * Get the login username to be used by the controller.
 *
 * @return string
 */
public function username()
{
    return 'email';
}
See, it’s just a constant field returned by a function. And then it is used in actual validation and authentication, in the same trait:
protected function validateLogin(Request $request)
{
    $request->validate([
        $this->username() => 'required|string',
        'password' => 'required|string',
    ]);
}
So all you need to do is override this method into your LoginController, similar to what we did with redirectTo parameter previously in this article.
class LoginController extends Controller
{
    use AuthenticatesUsers;
    // ... All other code

    public function username()
    {
        return 'username';
    }
}
Link : https://laraveldaily.com/9-things-you-can-customize-in-laravel-registration/

Laravel 6 Authentication Tutorial

Are you looking for make auth in laravel 6 then i will help you to make authentication using laravel ui package in laravel 6. i will explain to you how to create login and registration using auth in laravel 6.
Laravel 6 provide septate composer package for creating auth scaffold in laravel 6 application. Whenever you require to create auth in laravel 6 then you must have to install laravel/ui package in laravel 6.
Using laravel/ui you can create simple view with auth as same you did before you do. But you have to use vue js or react js with auth view in laravel 6. But they does not provide as default you have to follow few step to do auth.
You have to follow few step to make auth in your laravel 6 application.
First you need to install laravel/ui package as like bellow:
composer require laravel/ui
After that you can run following command and check ui commands info.
php artisan ui --help
Output:
Description:
Swap the front-end scaffolding for the application
Usage:
ui [options] [--]
Arguments:
type The preset type (bootstrap, vue, react)
Options:
--auth Install authentication UI scaffolding
--option[=OPTION] Pass an option to the preset command (multiple values allowed)
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
--env[=ENV] The environment the command should run under
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
You can use following commands for creating auth:
Using Vue:
php artisan ui vue --auth
Using React:
php artisan ui react --auth
Now you need to run npm command, otherwise you can not see better layout of login and register page.

Laravel 6 CRUD Application Tutorial

tep 1 : Install Laravel 6
first of all we need to get fresh Laravel 6 version application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Database Configuration
In second step, we will make database configuration for example database name, username, password etc for our crud application of laravel 6. So let's open .env file and fill all details like as bellow:
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3: Create Migration
we are going to create crud application for product. so we have to create migration for "products" table using Laravel 6 php artisan command, so first fire bellow command:
php artisan make:migration create_products_table --create=products
After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create products table.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('detail');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
Now you have to run this migration by following command:
php artisan migrate
Step 4: Add Resource Route
Here, we need to add resource route for product crud application. so open your "routes/web.php" file and add following route.
routes/web.php
Route::resource('products','ProductController');
Step 5: Add Controller and Model
In this step, now we should create new controller as ProductController. So run bellow command and create new controller. bellow controller for create resource controller.
php artisan make:controller ProductController --resource --model=Product
After bellow command you will find new file in this path "app/Http/Controllers/ProductController.php".
In this controller will create seven methods by default as bellow methods:
1)index()
2)create()
3)store()
4)show()
5)edit()
6)update()
7)destroy()
So, let's copy bellow code and put on ProductController.php file.
app/Http/Controllers/ProductController.php
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::latest()->paginate(5);
return view('products.index',compact('products'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
]);
Product::create($request->all());
return redirect()->route('products.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return view('products.show',compact('product'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function edit(Product $product)
{
return view('products.edit',compact('product'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Product $product)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
]);
$product->update($request->all());
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}
}
Ok, so after run bellow command you will find "app/Product.php" and put bellow content in Product.php file:
app/Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'name', 'detail'
];
}
Step 6: Add Blade Files
In last step. In this step we have to create just blade files. So mainly we have to create layout file and then create new folder "products" then create blade files of crud app. So finally you have to create following bellow blade file:
1) layout.blade.php
2) index.blade.php
3) create.blade.php
4) edit.blade.php
5) show.blade.php
So let's just create following file and put bellow code.
resources/views/products/layout.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 6 CRUD Application - ItSolutionStuff.com</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
resources/views/products/index.blade.php
@extends('products.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 6 CRUD Example from scratch - ItSolutionStuff.com</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('products.create') }}"> Create New Product</a>
</div>
</div>
</div>
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th>Details</th>
<th width="280px">Action</th>
</tr>
@foreach ($products as $product)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->detail }}</td>
<td>
<form action="{{ route('products.destroy',$product->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('products.show',$product->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edit</a>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
{!! $products->links() !!}
@endsection
resources/views/products/create.blade.php
@extends('products.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Add New Product</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('products.index') }}"> Back</a>
</div>
</div>
</div>
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('products.store') }}" method="POST">
@csrf
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Detail:</strong>
<textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
@endsection
resources/views/products/edit.blade.php
@extends('products.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Product</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('products.index') }}"> Back</a>
</div>
</div>
</div>
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('products.update',$product->id) }}" method="POST">
@csrf
@method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" value="{{ $product->name }}" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Detail:</strong>
<textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $product->detail }}</textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
@endsection
resources/views/products/show.blade.php
@extends('products.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2> Show Product</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('products.index') }}"> Back</a>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
{{ $product->name }}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Details:</strong>
{{ $product->detail }}
</div>
</div>
</div>
@endsection
Now we are ready to run our crud application example with laravel 6 so run bellow