Simple Tips to Getting Approved on ThemeForest

HTML markup validation:

Please check HTML markup validation before developing a theme.

WordPress Code:

The following functions must be present:

	
	wp_head() - just before </head>
	wp_footer() - just before </body>
	body_class() - inside <body> or <html> tags
	post_class()
  • WordPress theme files and directories must be named using lowercase letters. Words must be separated by hyphens, not camelCase or underscores.
  • Themes must not add any entries to the admin bar and must not remove, hide
  • The $content_width variable must be used to define the maximum allowed width for images, videos, and oEmbeds displayed within a theme
  • Default WordPress CSS classes must be covered in the stylesheet.
  • WP_Filesystem methods must be used where available instead of direct PHP filesystem calls. For example, mkdir, fopen, fread, fwrite, fputs, etc., must not be used.

Prefix Everything:

For my WordPress themes, I use the themename_ prefix all around, as it is simple and clean.

	<?php 

	// Functions
	function prefix_setup()
	
	// Classes
	class Prefix_Class {}

	// Global Variables
	global $prefix_passengers;

	// Action Hooks
	do_action( ‘prefix_start_engine’ );

	// Filter Hooks
	$register = apply_filters( prefix_register );

	// Non Third-Pary Script Handles
	wp_enqueue_script( 'prefix-functions', get_template_directory_uri() . 'js/custom/functions.js' );

	// Non Third-Pary Style Handles
	wp_enqueue_style( 'prefix-minified-style', get_template_directory_uri() . 'style.min.css' );

	// Images
	add_image_size( 'prefix-large', 800, 600 );

	?>		

Properly Include Scripts and Styles:

Do Not Prefix Third Party Scripts. Themes must use the scripts shipped with WordPress instead of including their own copy of the script or using one from a CDN. This includes jQuery, jQuery UI, Backbone, Underscore, etc. protocol-relative formats such as //example.com/file.js instead of http://example.com/file.js

	
	<?php

	/**
	 * Third Party Styles
	 * More info: https://github.com/grappler/wp-standard-handles
	 */
	 
	// Incorrect 
	wp_enqueue_style( 'prefix-font-awesome', get_template_directory_uri() . '/css/font-awesome.css', array(), '4.2.0', 'all' );

	// Corrrect 
	wp_enqueue_style( 'font-awesome', get_template_directory_uri() . '/css/font-awesome.css', array(), '4.2.0', 'all' );

	/**
	 * Third Party Scripts
	 */
	 
	// Incorrect 
	wp_enqueue_script( 'prefix-fitvids', get_template_directory_uri() . '/js/jquery.fitvids.js', array( 'jquery' ), '1.1.1', true );

	// Corrrect 
	wp_enqueue_script( 'jquery-fitvids', get_template_directory_uri() . '/js/jquery.fitvids.js', array( 'jquery' ), '1.1.1', true );

	?>	

Font Loading:

The fonts must be enqueued using wp_enqueue_style().

wp_enqueue_style( 'theme-prefix-fonts', "//fonts.googleapis.com/css?family=Lora:400,700|Inconsolata:700", '', '1.0.0', 'screen' );

Escape Everything:

	
	<?php

	// Use anytime HTML element encloses a section of data:
	echo esc_html( $no_html );

	// Use on all URLs, including those in the 'src' and 'href' attributes of an HTML element:
	<img src="<?php echo esc_url( $escaped_url ); ?>" />

	// Use for inline Javascript:
	<a href="#" onclick="<?php echo esc_js( $escaped_js ); ?>">
		<?php esc_html__( 'Click Here', 'text-domain' ); ?>
	</a>

	// Use for an HTML attribute:
	<div class="<?php echo esc_attr( $escaped_class ); ?>">

	?>		

Pluggable functions use:

A function can only be reassigned this way once, so you can’t install two plugins that plug the same function for different reasons. For safety, it is best to always wrap your functions with
if( ! function_exists(‘wp_mail’) ) { } , otherwise you will produce fatal errors on plugin activation.

PHP Code:

It is recommended that development is done with errors enabled and WP_DEBUG set to true. Follow the coding standard WordPress PHP Coding Standards.

  • Themes must work with the latest release of PHP. There is no required minimum supported version of PHP
  • The create_function() function has been deprecated as of PHP 7.2.0 and must no longer be used.
  • The “@” operator must not be used to suppress error messages or notices.
  • Tabs must be used for indentation
  • The creation of global variables is discouraged. They should be used only if absolutely necessary. If used, they must follow the prefixing rules.
  • The eval() function must not be used.

Check for PHP Errors and Warnings:

One of the easiest errors to check for is standard PHP errors. Enable wp_debug and go to town self-reviewing your theme to ensure there are no PHP errors, notices or warnings anywhere. You should also check for errors every time you submit an update.

HTML/CSS Code:

Note: It is strongly recommended that your theme follows both the WordPress HTML Coding Standards and the WordPress CSS Coding Standards.

  • CSS styling must not be hardcoded anywhere within a theme, either inline or in a tag.
  • A table of contents at the top of the stylesheet to act as a guide is required.
  • Dynamic styling must be added via wp_add_inline_style() with the exception of adding a background image to an element. In this instance, the following would be permitted:
  • 		<div id="header-background" style="background-image: url( <?php echo esc_url( '$header-background' ); ?> );"></div>
    	
  • IDs and classes must be appropriately named and follow a naming convention.
  • Strongly Recommended that all your code be run through the W3C validator. Items will be soft-rejected for important errors such as unclosed tags, nesting errors, duplicate IDs, etc.

JavaScript Code:

It is strongly recommended that your theme follow the WordPress JavaScript Coding Standards.

  • JavaScript code must be placed in external files whenever possible.
  • If defined in the global scope, all functions and variables should be prefixed with a unique identifier.
  • Unbind all event handlers before binding.
  • If PHP variables or data need to be passed to JavaScript, wp_localize_script() must be used.
  • If using jQuery, then .on() must be used instead of .click(), .bind(), .hover(), etc.
  • Development and debugging code such as console.log() must be removed.
  • Strict mode must be used for all JavaScript. For example, for jQuery:
	(function($) {
      "use strict";
      // your code here
   })(jQuery);

Translation Ready:

  • All theme text strings must be translatable
  • Text strings must not contain variables or constants
  • The text domain must use dashes rather than underscores and be lowercase plain-text.
  • Translation file should be in English and delivered as a .pot file. The .pot will contain all translation strings. The .pot file name should match the theme-slug (i.e. themeslug.pot).
  • Themes can include actual translation files (.po/.mo) for any variety of specific languages, but must not add the en_US.mo or en_US.po because English is already implied.

Theme Security Requirements:

Validation
Where possible, data must be validated on input. Although validation may occur on the client side, this cannot be solely relied on. The data also needs to be revalidated on the server side before the data is saved.
For more information on validation, refer to Data Validation article.Data Validation

Sanitization
If data cannot be validated on input, it must be sanitized instead.For example, it may not be possible to validate a text field, instead, it should be sanitized using the sanitize_text_field() or wp_kses() functions.For more information on sanitization, refer to Data Sanitization/Escaping

Working with the Database
Themes must not work directly with the database to create, update or delete site content and should generally only use WordPress core functions to display content.If there is a valid reason to work with the database, then the wpdb class provided by WordPress must be used. SQL statements must be prepared using $wpdb->prepare().

Escaping Output
WordPress core functions that return dynamic data must be escaped by the theme, except for those core functions starting with ‘the_’, which are generally escaped already. For example, home_url, admin_url, get_permalink, get_header_image, etc., should be escaped, but the_content, the_permalink, etc., are not required to be escaped.

Nonces
Any data that is submitted to the server must use nonces. If a user is allowed to submit data to the server, a nonce must be used to verify the origin and intent of the request.

SVG Upload
Themes must not enable SVG uploads as it raises security concerns due to the possibility of attackers executing malicious code through SVG’s XML.

Update TGMPA:

Keep in mind that every time you release a new version of your theme, you should double check that the latest version of TGMPA is included.

Properly Include Plugins Using TGMPA:

	<?php
	
	// Include a plugin from the WordPress Repository:
	array(
	  'name'      => esc_html__( 'WooCommerce', 'text-domain' ),
	  'slug'      => 'woocommerce',
	  'required'  => false,
	),

	// Include a plugin bundled within a WordPress theme:
	array(
	  'name'      => esc_html__( 'Example Plugin', 'text-domain' ),
	  'slug'      => 'example-plugin',
	  'source'    => get_template_directory() . '/inc/plugins/example-plugin.zip',
	  'required'  => false,
	),

	?> 	

Disable TGMPA Force Actions:

Every user should have free rein to activate or deactivate any WordPress plugins installed on their website.

Core Features:

1.Themes must not use features/APIs meant for WordPress core.
2.Themes must be widget-ready in all advertised locations. All widgetized areas must be appropriately styled to match the theme/demo design.
3.wp_nav_menu() must be included in at least one theme location. Menu locations may only display placeholders such as Add Menu and Set Menu if the current user is a logged in admin user and no menu has yet been set.
4.Themes must not unregister default WordPress widgets. Instead, new widgets should be registered via a plugin.
5.Must support all of the following features:

  • Comments
  • Sidebars
  • Editor style
  • Title tag

6.index.php must be reserved for the standard blog “latest posts” view.
7.Content, including placeholder/demo content, must not be hardcoded into the template files.
8.Admin code should be kept separate from public facing code via the is_admin() conditional to prevent unauthorized access.
9.Specify column names instead of * in your queries.

Menu Position:

If the theme has an Options page and no other sub menu items, then it must go in either the Customizer (strongly recommended) or the Appearance section.

Customizer:

Users are increasingly expecting to find theme options within the Customizer. All Customizer settings must be properly validated and sanitized with an appropriate sanitization callback.

Child Themes:

If a child theme is provided with the theme, it must:

  • Load the parent stylesheet using wp_enqueue_style() instead of @import.
  • Consist of style.css, functions.php and screenshot.png files at a minimum.
  • Append “Child” to the theme name so it can be identified as a child theme.

Plugin Territory Functionality:

  • Analytics code
  • SEO options
  • Forms
  • Non-design related meta boxes
  • Resource caching
  • Dashboard widgets
  • Custom Post Types
  • Custom Taxonomies
  • Shortcodes
  • Widgets
  • Social media like, follow and, share buttons
  • Framework related metabox

Third-Party Plugins & Libraries:

If you include plugins with your theme, you must use the TGM Plugin Activation (TGM PA) library.

  • You must keep included plugins and libraries up to date.
  • The force_activation and force_deactivation TGM PA parameters must not be set to true.
  • For plugins included in the zip file, the version TGM PA parameter must be set and kept up to date
  • You must not rename the original class-tgm-plugin-activation.php file to anything else.
  • Bundled plugins must be included in the main zip file.

Checking for Plugins:

Do not use is_plugin_active() when checking whether a plugin is active or not. is_plugin_active() is not reliable as it depends on the plugin’s folder/filename(which may change). Instead, you can use function_exists() or class_exists() as these are more reliable.

Import & Export Plugin:

Importers must not add content without user permission. Importers must not overwrite current content without clear warnings to the user. Custom Importers must use the WP Filesystem API.
Import/export functionality should be included via a plugin such as One Click Demo Import

Theme Unit Test Data:

Common issues are table display errors, image alignments, responsive comments, pingbacks display errors, password-protected post styling issues, and search index mishaps.

Run Theme Check:

Theme Check is literally the easiest way to check your WordPress theme against the latest coding standards and techniques. You can use Envato Theme Check plugin.

Provide Offline and online Documentation:

Documentation can be either publicly accessible online or included in the archive offline. Having offline documentation ensures that your customers are not hanging when there is not an Internet connection available or when your files are inaccessible – for any reason.

Advertisements

Admin login system own way

Routing:

web.php

Route::get('admin-login', 'Admin\Auth\LoginController@showLoginForm')->name('admin.login');
Route::post('admin-login', 'Admin\Auth\LoginController@login');

Controllers > Auth folder copy and paste it Controllers > Admin folder
Controllers > LoginController.php
Copy from AuthenticatesUsers.php and paste LoginController.php
You have to override that functions

<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
   
    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = 'admin/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    
    public function showLoginForm()
    {
        return view('admin.login');
    }

    public function login(Request $request)
    {
        $this->validateLogin($request);

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
    
    protected function guard()
    {
        return Auth::guard('admin');
    }
}

We need to create guard config > auth.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Model\admin\admin::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],


    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'admins' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

We need to define our model

<?php

namespace App\Model\admin;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class admin extends Authenticatable
{
    use Notifiable;
}

login.blade.php for view

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>AdminLTE 2 | Log in</title>
      <!-- Tell the browser to be responsive to screen width -->
      <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
      <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
      <!-- Google Font -->
      <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
   </head>
   <body class="hold-transition login-page">
      <div class="container">
         <div class="col-lg-4 offset-lg-4">
            <center>
               <h3>Admin Login</h3>
            </center>
            @include('includes.message')
            <form action="{{route('admin.login')}}" method="post">
               {{csrf_field()}}
               <div class="form-group has-feedback">
                  <input type="email" class="form-control" name="email" placeholder="Email">
                  <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
               </div>
               <div class="form-group has-feedback">
                  <input type="password" class="form-control" name="password" placeholder="Password">
                  <span class="glyphicon glyphicon-lock form-control-feedback"></span>
               </div>
               <div class="form-group">
                  <div class="col-xs-8">
                     <div class="checkbox icheck">
                        <label>
                        <input type="checkbox"> Remember Me
                        </label>
                     </div>
                  </div>
                  <div class="col-xs-4">
                     <button type="submit" class="btn btn-primary">Sign In</button>
                  </div>
               </div>
            </form>
            <a href="{{ route('password.request') }}">
            Forgot Your Password?
            </a>
         </div>
      </div>
   </body>
</html>

আপনি কি বেশি খুঁতখুঁতে?

বারবার হাত ধোয়া, ঘর থেকে বেরিয়ে চুলা নেভানো হয়েছে কি না—তা দেখতে আবার ঘরে ঢোকা, খাওয়ার আগে ধোয়া প্লেট বা গ্লাস আবার ধোয়া—কখনো কখনো কারও মধ্যে এ রকম একই চিন্তা, অনুভূতি বা কাজের ইচ্ছা থাকে। তৈরি হয় উৎকণ্ঠা আর তীব্র মানসিক চাপ। জীবনকে করে তোলে বিষময়। আক্রান্ত ব্যক্তি এসব চিন্তা, অনুভূতিকে দমন করতে চায়, এড়িয়ে চলতে চায়। এ জন্য একই কাজ বারবার করতে শুরু করে। মানসিক স্বাস্থ্যের এই সমস্যার নাম অবসেসিভ কম্পালসিভ ডিসঅর্ডার (ওসিডি), যা সাধারণ পরিচ্ছন্নতা বা সাধারণ গুছিয়ে রাখার প্রবণতার মতো নয়, তার চাইতে অনেক বেশি, যেটি রীতিমতো রোগের পর্যায়ে পড়ে।

এই চিন্তা ও আচরণ মনের মধ্য থেকেই তৈরি হয়। রোগী নিজেও বুঝতে পারে যে এগুলো ভিত্তিহীন বা অযৌক্তিক, কিন্তু তা–ও চিন্তাটা সরাতে পারে না। এগুলোর পেছনে প্রতিদিন অনেক কর্মঘণ্টা নষ্ট হয়। কাজকর্মও ব্যাহত হয়। শরীর নোংরা হওয়ার ভয়, অহেতুক সন্দেহ, কোনো অমূলক শারীরিক সমস্যা নিয়ে চিন্তা, সবকিছুর মধ্যে নিখুঁত সামঞ্জস্য তৈরি করার ভাবনা, বিনা কারণে উত্তেজিত হয়ে যাওয়া, অস্বাভাবিক ও অতিরিক্ত যৌন চিন্তা, ধর্মীয় বিষয়ে অস্বাভাবিক চিন্তা, বারবার একই জিনিস পরীক্ষা করা (দরজা বন্ধ কি না, তা অনেকবার দেখা), অসংখ্যবার হাত ধোয়া, বেশি সময় ধরে গোসল করা বা বাথরুমে থাকা, কোনো কিছু বারবার গোনা (অনেকবার টাকা গুনে দেখা), একই প্রশ্ন বারবার করা, সবকিছু নিখুঁতভাবে সাজিয়ে রাখার চেষ্টা করা, প্রয়োজনীয়-অপ্রয়োজনীয় সবকিছু সংগ্রহে রাখা অর্থাৎ পরে কাজে লাগতে পারে ভেবে অপ্রয়োজনীয় বস্তুটিও ফেলে না দেওয়া ইত্যাদি হচ্ছে ওসিডির সাধারণ লক্ষণ। ওসিডি দমন করতে না পেরে আগ্রাসী আচরণ বা অত্যধিক রাগ হতে পারে কারও কারও।
পরিবারের কেউ এমন আচরণ করলে হেসে উড়িয়ে দেওয়ার কিছু নেই। ভাববেন না যে ও তো এ রকমই, একটু বেশি শুচিবায়ু বা খুঁতখুঁতে।

ওসিডি একটি রোগ এবং এর সুনির্দিষ্ট চিকিৎসা রয়েছে। চার থেকে আট সপ্তাহের মধ্যে ওষুধের প্রভাবে কিছুটা উন্নতি দেখা দিতে পারে। তবে পুরোপুরি ফল পেতে অপেক্ষা করতে হয় কয়েক মাস। ওষুধের পাশাপাশি ধারণা ও আচরণ পরিবর্তনকারী চিকিৎসা (কগনিটিভ-বিহেভিয়ার থেরাপি) এ রোগের জন্য বিশেষ কার্যকরী।

উৎস: প্রথম আলো

File Storage

The public disk is intended for files that are going to be publicly accessible. By default, the public disk uses the local driver and stores these files in storage/app/public. To make them accessible from the web, you should create a symbolic link from public/storage to storage/app/public.

To create the symbolic link, you may use the storage:link Artisan command:

php artisan storage:link

File Uploads

if ($request->hasFile('image')) {
    $fileName =  $request->image->store('public');
}
$post->image  = $fileName;
$post->save();

Retrieving Files

File URLs

use Illuminate\Support\Facades\Storage;
$image_src  = Storage::url($post->image);
return $image_src;

or

return Storage::disk('local')->url($post->image)

Laravel 5.5 Socialite for all

Create a Laravel Authentication

php artisan make:auth

Download the laravel socialite package

composer require laravel/socialite

Configuration

These credentials should be placed in your config/services.php configuration file

    'facebook' => [
        'client_id' => '337690530037',         // Your Facebook Client ID
        'client_secret' => 'f4c9f04c3344c7ef222526e2cc506', // Your Facebook Client Secret
        'redirect' => 'http://localhost:8000/login/facebook/callback',
    ], 
    'twitter' => [
        'client_id' => 'ZcY9XQU3kKJ8pktOhSgjWNJ',         // Your twitter Client ID
        'client_secret' => 'cK0m6pUZJrGjpslvgHWXVjz88q0ND7FAyEzcMi', // Your twitter Client Secret
        'redirect' => 'http://127.0.0.1:8000/login/twitter/callback',
    ],
    'google' => [
        'client_id' => '857054384681-jvq9c3bvtho429b7.apps.googleusercontent.com',   // Your google Client ID
        'client_secret' => 'MOG_QYsclYiZ11wXxqTrtn', // Your google Client Secret
        'redirect' => 'http://localhost:8000/login/google/callback',
    ],

Routing

Next, you are ready to authenticate users! You will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication. We will access Socialite using the Socialite facade:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
    
    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

   /**
     * Redirect the user to the authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }


    /**
     * Obtain the user information from authentication.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback($provider)
    {
        if ($provider == 'twitter') {
            $user = Socialite::driver('twitter')->user();
        } elseif($provider == 'facebook') {
            $user = Socialite::driver('facebook')->user();            
        }else{
            $user = Socialite::driver('google')->stateless()->user();
        }       
                
        $findUser = User::where('email', $user->email)->first();
        if ($findUser) {
            Auth::login($findUser);            
        } else {
            $newuser           = new User;
            $newuser->name     = $user->name;
            $newuser->email    = $user->email;
            $newuser->password = bcrypt(123456);
            $newuser->save();
            Auth::login($newuser);            
        }
        return redirect('home');
    }

}

Of course, you will need to define routes to your routing file routes > web.php

Route::get('login/{provider}', 'Auth\LoginController@redirectToProvider');
Route::get('login/{provider}/callback', 'Auth\LoginController@handleProviderCallback');

Edit your existing login view resources/views/auth/login.blade.php and add following HTML code.

<div class="panel-body">              
    <div class="panel-body">
        <a class="btn btn-primary" href="{{'/login/facebook'}}">
           {{'Facebook Login'}}
        </a>
        <a class="btn btn-primary" href="{{'/login/twitter'}}">
            {{'Twitter Login'}}
        </a>
        <a class="btn btn-primary" href="{{'/login/google'}}">
            {{'Google Plus'}}
        </a>
    </div>
</div>   

Laravel Socialite Facebook Login

Create a Users table

We need to run database migrations to create user table but before doing that we need to modify it to store OAuth user.

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password')->nullable(); // Set to nullable
        $table->string('token'); // OAuth Token
        $table->rememberToken();
        $table->timestamps();
    });
}

Create a Laravel Authentication

php artisan make:auth

Download the laravel socialite package

composer require laravel/socialite

Create Facebook App To Get Tokens

Go to the Facebook’s developers portal by following URL: https://developers.facebook.com/
Login via your Facebook account.

Create a new app then select facebook login product. After that, you can see the App id and App secret. You need to fill up some fields. Something like that

Configuration

Before using Socialite, you will also need to add credentials for the OAuth services your application utilizes. These credentials should be placed in your config/services.php configuration file

 'facebook' => [
        'client_id' => '3376905368878457',         // Your Facebook Client ID
        'client_secret' => 'f4c9f04c3344c7ef543222526e7874545', // Your Facebook Client Secret
        'redirect' => 'http://localhost:8000/login/facebook/callback',
    ],

Routing

Next, you are ready to authenticate users! You will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication. We will access Socialite using the Socialite facade:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
 
    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Redirect the user to the facebook authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider()
    {
        return Socialite::driver('facebook')->redirect();

    }

    /**
     * Obtain the user information from facebook.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback()
    {
        $userSocial = Socialite::driver('facebook')->user();
        //return $userSocial->getId();
        //return $userSocial->getName();
        $findUser = User::where('email', $userSocial->email)->first();
        if ($findUser) {
            Auth::login($findUser);
            return "done with old";
        } else {
            $user           = new User;
            $user->name     = $userSocial->name;
            $user->email    = $userSocial->email;
            $user->password = bcrypt(123456);
            $user->save();
            Auth::login($user);
            return "done with new";
        }
    }
}

Of course, you will need to define routes to your controller methods:

Route::get('login/facebook', 'Auth\LoginController@redirectToProvider');
Route::get('login/facebook/callback', 'Auth\LoginController@handleProviderCallback');

Now we’ll be adding a link to our existing login form that will take the user to facebook authentication page. Edit your existing login view resources/views/auth/login.blade.php and add following HTML code.

<div class="panel-body">                         
    <div class="panel-heading">Login with Facebook</div>                            
    <div class="panel-body">
        <a class="btn btn-primary" href="{{'/login/facebook'}}">
            Facebook Login
        </a>
    </div>
</div>

Form Request Validation

Creating Form Requests

The generated class will be placed in the app/Http/Requests directory.

php artisan make:request StoreFormValidation

You can use a switch statement for multiple validations.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreFormValidation extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        /*return [
            'title' => 'required|unique:todos',
            'body' => 'required'
        ];*/

        switch ($this->method()) {
            case 'GET':
            case 'DELETE':
            {
                return [];
            }
            case 'POST':
            {
                return [
                    'title' => 'required|unique:todos|max:50',
                    'body' => 'required',
                ];
            }
            case 'PUT':
            case 'PATCH':
            {
                return [
                    'title' => 'required|max:50',
                    'body' => 'required',
                ];
            }            
            default:               
                break;
        }
    }
}

How are the validation rules evaluated?

public function store(StoreFormValidation $request)
{
    // The incoming request is valid...
}

public function update(StoreFormValidation $request, $id)
{
    // The incoming request is valid...
}

Laravel Pagination

Pagination Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\user;

class Pagination extends Controller
{
    public function paginate(){
    	// $users = User::all();
    	$users = User::paginate(8);
    	return view('pagination',compact('users'));
    }
}

Routing: routes > web.php

Route::get('list','Pagination@paginate');

pagination.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Pagination</title>
	<link rel="stylesheet" href="/css/bootstrap.css" crossorigin="anonymous">
</head>
<body>
	<div class="container">
		<div class="row">
			<div class="col-lg-6 offset-lg-3">
				<center><h2>Laravel Pagination</h2></center>
				<table class="table table-hover">
					<thead>
						<tr>
							<th scope="col">No</th>
							<th scope="col">Name</th>
							<th scope="col">Email</th>      
						</tr>
					</thead>
					<tbody>   
						@foreach ($users as $user)
							<tr>      
								<td>{{$loop->index+1}}</td>
								<td>{{$user->name}}</td>
								<td>{{$user->email}}</td>
							</tr>
						@endforeach						
					</tbody>				
				</table> 
				<div>
					{{$users->links()}}					
				</div>
			</div>
		</div>
	</div>
</body>
</html>

Customizing The Pagination View

However, the easiest way to customize the pagination views is by exporting them to your resources/views/vendor directory using the vendor:publish command:

php artisan vendor:publish --tag=laravel-pagination

This command will place the views in the resources/views/vendor/pagination directory. The default.blade.php file within this directory corresponds to the default pagination view. Edit this file to modify the pagination HTML.

Using default bootstrap

{{$users->links("pagination::bootstrap-4")}}

Database: Seeding

To create fake data inside the Database, you can use seeding. All seed classes are stored in the database/seeds directory.

To generate a seeder

php artisan make:seeder UserSeeder

Writing Factories

To get started, take a look at the database/factories/UserFactory.php file in your application.

<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
        'remember_token' => str_random(10),
    ];
});

$factory->define(App\Test::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'user_id' => rand(1,100),                
    ];
});

Using Model Factories

<?php

use Illuminate\Database\Seeder;

class TestSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Test::class, 10)->create();
    }
}

<?php

use Illuminate\Database\Seeder;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class, 10)->create();
    }
}

Calling Additional Seeders

Within the DatabaseSeeder class, you may use the call method to execute additional seed classes.

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //$this->call(TestSeeder::class);
        //$this->call(UserSeeder::class);
        $this->call([
        	TestSeeder::class,
        	UserSeeder::class
        ]);       
    }
}

Running Seeders


php artisan db:seed

or 

php artisan db:seed --class=UserSeeder

Once you have written your seeder, you may need to regenerate Composer’s autoloader using the dump-autoload command:

composer dump-autoload

Middleware

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen.

Whenever there is request by a user then request has to go first on the middleware and when middleware authorized that request then it will go to the backend.

Defining Middleware

cd DirectoryName
php artisan make:middleware MiddlewareName

after creating middleware

<?php

namespace App\Http\Middleware;

use Closure;

class test
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $ip = $request->ip();
        if($ip == '127.0.0.1'){
            throw new \Exception("your IP is correct");            
            //return redirect('/');
        }
        return $next($request);
    }
}

Assigning Middleware To Routes:

Route::get('about', function () {
    return view('about');
})->middleware('test');

Registering Middleware

If you want a middleware to run during every HTTP request to your application, you should first assign the middleware a key in your app/Http/Kernel.php file.

protected $routeMiddleware = [    
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'test' => \App\Http\Middleware\test::class,
];