Laravel 8 Socialite Login with Google Gmail Account

Laravel 8 Socialite Login with Google Gmail Account

Hello Dev,

Today, I can provide an explanation for you grade by grade login with google account in laravel 8 using socialite. laravel 8 socialite offer api to login with gmail account. you could without difficulty login the usage of google account in laravel 8 utility.

As we understand social media is a end up more and more famous within the global. each one have social account like gmail, facebook and so forth. i think additionally maximum of have gmail account. So if to your application have login with social then it come to be first-rate. you bought more people hook up with your internet site because maximum of people does no longer want to fill join up or register shape. If there login with social than it turn out to be remarkable.

So if you want to also implement login with google gmail account then i will help you step by step instruction. let's follow tutorial and implement it.

Step 1 : Install Laravel 8

In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

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. So lets open .env file and fill all deatils 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 : Install Jetstream

Here we need auth scaffolding of jetstream. i will give full example for how to install jetstream so click here.

Step 4 : Install Socialite

In this step, we need laravel/socialite package. you can install socialite package using bellow command so let's run bellow command :

composer require laravel/socialite

After install above package you can add providers and aliases in config file, Now open config/app.php file and add service provider and aliase.

config/app.php
....

'providers' => [
    ....
    Laravel\Socialite\SocialiteServiceProvider::class,
],

'aliases' => [
    ....
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],

....
Step 5: Create Google App

Here we need google client id and secret that way we can get information of other user. so if you don't have google app account then you can create from here : Google Developers Console. you can find bellow screen :

Laravel 8 Socialite Login with Google Gmail Account

Now you have to click on Credentials and choose first option oAuth and click Create new Client ID button. now you can see following slide:

Laravel 8 Socialite Login with Google Gmail Account
Laravel 8 Socialite Login with Google Gmail Account

after create account you can copy client id and secret.

Now you have to set app id, secret and call back url in config file so open config/services.php and set id and secret this way:

config/services.
return [
    ....
    'google' => [
        'client_id' => 'app id',
        'client_secret' => 'add secret',
        'redirect' => 'http://localhost:8000/auth/google/callback',
    ],
]
Step 6: Add Database Column

In this step first we have to create migration for add google_id in your user table. So let's run bellow command:

php artisan make:migration add_google_id_column_in_users_table  --table=users
database/migrations/2020_09_18_052105_add_google_id_column_in_users_table.php
<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
class AddGoogleIdColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('google_id')->nullable();
        });
    }
   
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('google_id');
         });
    }
}

Update mode like this way:

app/Models/User.php
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'google_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}
Step 7: Create Routes

Here, we need to add resource route for login with gmail account. so open your "routes/web.php" file and add following route.

routes/web.php
use App\Http\Controllers\Auth\GoogleController;

Route::get('auth/google', [GoogleController::class, 'redirectToGoogle']);
Route::get('auth/google/callback', [GoogleController::class, 'handleGoogleCallback']);
Step 8: Create Controller

After add route, we need to add method of google auth that method will handle google callback url and etc, first put bellow code on your GoogleController.php file

app/Http/Controllers/Auth/GoogleController.php
<?php
  
namespace App\Http\Controllers\Auth;
  
use App\Http\Controllers\Controller;
use Socialite;
use Auth;
use Exception;
use App\Models\User;
  
class GoogleController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }
      
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleGoogleCallback()
    {
        try {
    
            $user = Socialite::driver('google')->user();
     
            $finduser = User::where('google_id', $user->id)->first();
     
            if($finduser){
     
                Auth::login($finduser);
    
                return redirect('/dashboard');
     
            }else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'google_id'=> $user->id,
                    'password' => encrypt('123456dummy')
                ]);
    
                Auth::login($newUser);
     
                return redirect('/dashboard');
            }
    
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}
Step 9: Update Blade File

Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code:

resources/views/auth/login.blade.php
<x-guest-layout>
    <x-jet-authentication-card>
        <x-slot name="logo">
            <x-jet-authentication-card-logo />
        </x-slot>

        <x-jet-validation-errors class="mb-4" />

        @if (session('status'))
            <div class="mb-4 font-medium text-sm text-green-600">
                {{ session('status') }}
            </div>
        @endif

        <form method="POST" action="{{ route('login') }}">
            @csrf

            <div>
                <x-jet-label value="{{ __('Email') }}" />
                <x-jet-input class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
            </div>

            <div class="mt-4">
                <x-jet-label value="{{ __('Password') }}" />
                <x-jet-input class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
            </div>

            <div class="block mt-4">
                <label class="flex items-center">
                    <input type="checkbox" class="form-checkbox" name="remember">
                    <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
                </label>
            </div>

            <div class="flex items-center justify-end mt-4">
                @if (Route::has('password.request'))
                    <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}">
                        {{ __('Forgot your password?') }}
                    </a>
                @endif

                <x-jet-button class="ml-4">
                    {{ __('Login') }}
                </x-jet-button>

                    <a href="{{ url('auth/google') }}" style="margin-top: 0px !important;background: green;color: #ffffff;padding: 5px;border-radius:7px;" class="ml-2 btn-google">
                      <strong>Login With Google</strong>
                    </a> 
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

Now we are ready to run laravel 8 socialite login with Google gmail account so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/login
Output
Laravel 8 Socialite Login with Google Gmail Account

It will help you...

Laravel Scout Algolia Full Text Search Example

Hi Guys

Today,I will tell how you can full text search utilizing scout algolia. i will show the example of laravel scout algolia full text search.you can full text search utilizing scout algolia api.it can this example full expound scout algolia full text search.

I will show the rudimental step of scout algolia api full text search.if you can utilize full text search for install scout and Algolia api package.we are utilizing algolia api utilizing full text search example in laravel.

Here the following steps example laravel full text search Using scout algolia

Step 1: Create Laravel Project

In this step create laravel project following command.

composer create-project --prefer-dist laravel/blog
Step 2: Database Configuration

After create laravel project , we require to make database configuration, you have to add following details on your .env file.

1.Database Username

1.Database Password

1.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:

following path: .env
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 3: Install Scout Package

In this step you are install scout package blow the command.

composer require laravel/scout

After installing Scout, you should publish the Scout configuration using the vendor: publish Artisan command.

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

Running a queue worker will allow Scout to queue all operations that sync your model information to your search indexes, providing much better response times for your application’s web interface.

Set the value of queue in the .env file.

following path: .env
SCOUT_QUEUE = true
Step 4: Install Algolia Driver.

you will also want to install the algolia php sdk via the composer package manager,

composer require algolia/algoliasearch-client-php

Next, we have to set id and secret of Algolia. So move to this website Algolia and then create your account.

After login, You can get id and secret from this link: https://www.algolia.com/api-keys

Laravel Scout Algolia Full Text Search Example

You can set id and secret in your .env file.

Set the value of queue in the .env file.

following path: .env
ALGOLIA_APP_ID = Enter your Application ID
ALGOLIA_SECRET = Enter your Admin API Key
Step 5: Create Posts Table and Model

In this step we have to create migration for posts table using Laravel project php artisan command, so first fire bellow command:

php artisan make:model Post -m

After this command you have to put bellow code in your migration file for create posts table.

following path:/database/migrations/2020_01_10_102325_create_posts_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('body');
            $table->string('category');
            $table->integer('view');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your model file for create Post table.

following path:/app/Post.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Post extends Model
{
	use Searchable;

    protected $fillable = ['title','body','category','view'];
     /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function searchableAs()
    {
        return 'post_index';
    }
}
Step:6 Batch Import

In this step insert some records database records need to import into your search driver. scout provides an artisan command that you may use to import all of your existing records into your search indexes.

php artisan scout:import "App\Post"
Step 7: Create Route

In this is step we need to create route for post search layout file

following path:/routes/web.php
Route::get('index','SearchController@search');
Step 8: Create Controller

here this step now we should create new controller as SearchController,So run bellow command for generate new controller

php artisan make:controller SearchController

now this step, this controller will manage layout post search request,bellow content in controller file.following fille path

following path:/app/Http/Controllers/SearchController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class SearchController extends Controller
{
    public function search(Request $request)
    {
    	if($request->has('search')){
    		$posts = Post::search($request->get('search'))->get();	
    	}else{
    		$posts = Post::get();
    	}
        return view('index', compact('posts'));
    }
}
Step 9: Create a View File

In this step, let's create index.blade.php(resources/views/index.blade.php) for layout and we will write design code here and also post search and recored table, So put following code:

following path:resources/views/index.blade.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Laravel Scout Search Tutorial </title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">    
</head>
<body>
    <div class="container">
        <h1>Laravel Scout Search Tutorial</h1>
        <div class="row">
            <div class="col-md-6">
                <form method="GET" action="{{ url('index') }}">
                    <div class="row">
                        <div class="col-md-10">
                            <input type="text" name="search" class="form-control" placeholder="Search">
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-info">Search</button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="col-md-4 ">
                <a href="{{ url('index') }}" class="btn btn-danger">Cancel</a>
            </div>
        </div>
   <br/>
      <table class="table table-bordered">
            <tr>
                <th>Id</th>
                <th>Title</th>
                <th>Body</th>
                <th>Category</th>
                <th>View</th>
            </tr>
            @if(count($posts) > 0)
                @foreach($posts as $post)
                <tr>
                    <td>{{ $post->id }}</td>
                    <td>{{ $post->title }}</td>
                    <td>{{ $post->body }}</td>
                    <td>{{ $post->category }}</td>
                    <td>{{ $post->view }}</td>
                </tr>
                @endforeach
            @else
            <tr>
                <td colspan="5" class="text-danger">Result not found.</td>
            </tr>
            @endif
        </table>
   </div>
</body>
</html>

Now we are ready to run our example so run bellow command so quick run:

php artisan serve
http://localhost:8000/index

It will help you...

Laravel Migration Add Comment to Column Example

Laravel Migration Add Comment to Column Example

Hi Dev,

Today, This blog is focused on laravel migration add comment to table. This tutorial will give you simple example of laravel migration add comment to table. i would like to show you laravel migration add comment to existing column.

laravel migration provide comment() where you can add comment to table column. so let's see both example. you can easily set laravel 8 version.

Create Table Column with Comment
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('pages', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('rank')->comment("page rank detail");
            $table->integer('stock');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('pages');
    }
}

Existing Table Column with Comment

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class AddNewColumnAdd2 extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('pages', function (Blueprint $table) {
            $table->string('stock')->comment("Page stock detail")->change();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        
    }
}

It Will help You...

Laravel 8 Barcode Generator Example

Laravel 8 Barcode Generator Example

Hi Dev

Today,I will learn you how engender barcode in laravel 8 we will show barcode engenderer example in laravel 8.I will engenderer barcode useing milon/barcode package in laravel 8. laravel 8 barcode engenderer example. in this tutorial, i would relish to show you how to engender or engender barcode in laravel 8 utilizing milon/barcode package.

In this blog, i will utilize milon/barcode package to engender simple, text, numeric and image barcode in laravel 8 app.

Step 1 : Install Laravel 8 Application

we are going from scratch, So we require to get fresh Laravel 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 this step, configure database with your downloded/installed laravel 8 app. So, you need to find .env file and setup database details as following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password
Step 3 :Installing Barcode Generator Package

Now In this step, install milon/barcode package in laravel 8 app via following command.

composer require milon/barcode
Step 4:Configure Barcode Generator Package

Here In this step,I will configure the milon/barcode package in laravel 8 app. So, Open the providers/config/app.php file and register the provider and aliases for milon/barcode.

'providers' => [
    ....
    Milon\Barcode\BarcodeServiceProvider::class,
],
  
'aliases' => [
    ....
    'DNS1D' => Milon\Barcode\Facades\DNS1DFacade::class,
    'DNS2D' => Milon\Barcode\Facades\DNS2DFacade::class,
]
Step 5:Create Routes

In this step,we will add the bar code generation routes in web.php file, which is located inside routes directory:

use App\Http\Controllers\BarcodeController;
Route::get('/barcode', [BarcodeController::class, 'index'])->name('barcode.index');
Step 6: Creating BarCode Controller

Now this step,I will create generate barcode controller file by using the following command.

php artisan make:controller BarCodeController

After navigate to app/http/controllers and open BarCodeController.php file. And add the simple barcode generation code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BarcodeController extends Controller
{
    public function index()
    {
      return view('barcode');
    }
}
Step 7 :Create Blade View

In this last step , create barcode-generator blade view file inside resources/views directory. And then add the following code into it.

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 8 Barcode Generator</title>
</head>
<body>
<div class="container text-center">
  <div class="row">
    <div class="col-md-8 offset-md-2">
       <h1 class="mb-5">Laravel 8 Barcode Generator</h1>
       <div>{!! DNS1D::getBarcodeHTML('4445645656', 'C39') !!}</div></br>
       <div>{!! DNS1D::getBarcodeHTML('4445645656', 'POSTNET') !!}</div></br>
       <div>{!! DNS1D::getBarcodeHTML('4445645656', 'PHARMA') !!}</div></br>
       <div>{!! DNS2D::getBarcodeHTML('4445645656', 'QRCODE') !!}</div></br>
    </div>
  </div>
</div>
</body>
</html>

Now we are ready to run our custom validation rules example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/barcode

It will help you..

Laravel 8 Login with Github Example

laravel 8 login with Github account

Hi Men

These days, I can give an explanation for you step by step login with Github Account in laravel 8 the usage of socialite. laravel eight socialite provide api to login with github account. you could effortlessly login using Github in laravel eight utility.

As we realize social media is a turn out to be increasingly popular inside the global. each one have social account like github, facebook and so forth. i suppose also most of have github account. So if for your utility have login with social then it grow to be exceptional. to procure more humans hook up with your website because most of human beings does not need to fill sign on or check in form. If there login with social than it end up splendid.

So in case you want to also enforce login with github account then i can assist you grade by grade education. let's comply with educational and implement it.

Step 1 : Install Laravel 8

Inside the first step, we need to get clean laravel 8 model software So permit's open terminal and run bellow command to put in clean laravel assignment.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration

In second step, we will make database Configuration as an instance database call, username, password and many others. So we could open .env record and fill all deatils 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 : Install Jetstream

Here we need auth scaffolding of jetstream. i will give full example for how to install jetstream so click here.

Step 4 : Install Socialite In this step, we need laravel/socialite package. you can install socialite package using bellow command so let's run bellow command :
composer require laravel/socialite

After install above package you can add providers and aliases in config file, Now open config/app.php file and add service provider and aliase.

config/app.php
....

'providers' => [
    ....
    Laravel\Socialite\SocialiteServiceProvider::class,
],

'aliases' => [
    ....
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],

....
Step 5: Create Github Api

Here we need Github account that way we can get information of other user. so if you don't have Github account then you can create from here : Github. you can find bellow screen :

Laravel 8 Login with Github Example

Now you have to click on Developer settings

Laravel 8 Login with Github

Next you have to click on OAuth Apps

laravel 8 socialite Github login

Here you have to click on Register a new application

 Github login with laravel 8

Here you have to create on Register a new OAuth application

login with gmail laravel 8

Now Redy Github APi

laravel 8 socialite Github tutorial

Now you have to set app id, secret and call back url in config file so open config/services.php and set id and secret this way:

config/services.php
	return [
    ....
    'github' => [
        'client_id' => 'app id',
        'client_secret' => 'add secret',
        'redirect' => 'http://your-callback-url',
    ],
]
Step 6: Add Database Column

In this step first we have to create migration for add Github Id in your user table. So let's run bellow command:

php artisan make:migration add_github_id_column
<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
class AddGithubIdColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('github_id')->nullable();
        });
    }
   
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('github_id');
         });
    }
}
Update mode like this way: app/Models/User.php
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'github_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}
Step 7: Create Routes

Here, we need to add resource route for login with gmail account. so open your "routes/web.php" file and add following route.

routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\GithubController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('auth/github', [GithubController::class, 'redirectToGithub']);
Route::get('auth/github/callback', [GithubController::class, 'handleGithubCallback']);
Step 8: Create Controller

After add route, we need to add method of github auth that method will handle github callback url and etc, first put bellow code on your GithubController.php file

app/Http/Controllers/Auth/GithubController.php
<?php
  
namespace App\Http\Controllers\Auth;
  
use App\Http\Controllers\Controller;
use Socialite;
use Auth;
use Exception;
use App\Models\User;
  
class GithubController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGithub()
    {
        return Socialite::driver('github')->redirect();
    }
      
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleGithubCallback()
    {
        try {
    
            $user = Socialite::driver('github')->user();
     
            $finduser = User::where('github_id', $user->id)->first();
     
            if($finduser){
     
                Auth::login($finduser);
    
                return redirect('/home');
     
            }else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'github_id'=> $user->id,
                    'password' => encrypt('123456dummy')
                ]);
    
                Auth::login($newUser);
     
                return redirect('/home');
            }
    
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}
Step 9: Update Blade File

Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code:

resources/views/auth/login.blade.php
<x-guest-layout>
    <x-jet-authentication-card>
        <x-slot name="logo">
            <x-jet-authentication-card-logo />
        </x-slot>

        <x-jet-validation-errors class="mb-4" />

        @if (session('status'))
            <div class="mb-4 font-medium text-sm text-green-600">
                {{ session('status') }}
            </div>
        @endif

        <form method="POST" action="{{ route('login') }}">
            @csrf

            <div>
                <x-jet-label value="{{ __('Email') }}" />
                <x-jet-input class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
            </div>

            <div class="mt-4">
                <x-jet-label value="{{ __('Password') }}" />
                <x-jet-input class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
            </div>

            <div class="block mt-4">
                <label class="flex items-center">
                    <input type="checkbox" class="form-checkbox" name="remember">
                    <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
                </label>
            </div>

            <div class="flex items-center justify-end mt-4">
                @if (Route::has('password.request'))
                    <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}">
                        {{ __('Forgot your password?') }}
                    </a>
                @endif

                <x-jet-button class="ml-4">
                    {{ __('Login') }}
                </x-jet-button>

                <a href="{{ url('auth/github') }}" style="margin-top: 0px !important;background: green;color: #ffffff;padding: 5px;border-radius:7px;" class="ml-2">
                  <strong>Login With Github</strong>
                </a> 
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>
Now we are ready to run our form validation example with laravel 8 so run bellow command for quick run:
php artisan serve
Now you can open bellow URL on your browser:
localhost:8000/login
You will see layout as like bellow: Output
socialite Github laravel 8

It will help you...

React Native Paper Menu Tutorial

React Native Paper Menu Tutorial

Hi Guys,

Today, I'm able to study you a way to engender paper menu in react native. you can facilely engender paper menu in react native. First i will import stylesheet namespace from react-local-paper, after i can make paper menu utilizing in react native.

Here, I can give you full instance for simply exhibit paper menu using react native as bellow.

Step 1 - Create project

In the first step Run the following command for create project.

expo init PaperMenu
Step 2 - Install Package

In the step,I will install npm i react-native-paper package.

npm i react-native-paper
Step 3 - App.js

In this step, You will open App.js file and put the code.

import React, { Component } from "react";
import { Text, View,StyleSheet} from 'react-native';
import { Provider ,Appbar,Card,menu} from 'react-native-paper';

const ItWebtutsComponent = () => {

   const [searchQuery, setSearchQuery] = React.useState('');

  const onChangeSearch = query => setSearchQuery(query);

  const _goBack = () => console.log('Went back');

  const _handleSearch = () => console.log('Searching');

  const _handleMore = () => console.log('Shown more');

  return (
    <Provider>
    <Appbar.Header style={styles.header}>
      <Appbar.BackAction onPress={_goBack} />
      <Appbar.Content title="User" subtitle="Subtitle" />
      <Appbar.Action icon="magnify" onPress={_handleSearch} />
      <Appbar.Action icon="dots-vertical" onPress={_handleMore} />
    </Appbar.Header>
      <View style={styles.mainbox}>
       <Card>
        <menu
            placeholder="Search"
            onChangeText={onChangeSearch}
            value={searchQuery}
          />
       </Card>
      </View>
    </Provider>
  );
};


const styles = StyleSheet.create({
  title:{
    margin: 10,
    fontSize: 15,
    fontSize: 35
  },
  mainbox:{
    textAlign:'center',
    margin: 15,
    flex: 1,
    justifyContent: 'space-between',
  },
  databeBox:{
    margin: 10,
    textAlign: 'center',
  },
  databeHeader:{
    margin: 10,
    textAlign: 'left', 
  }
});
export default ItWebtutsComponent;
Step 4 - Run project

In the last step run your project using bellow command.

expo start

It will help you...

Laravel IP Address Using Get Location Example

Laravel IP Address Using Get Location Example

Hi Dev,

Today,I will learn you how to get location useing ip address in laravel. we will show example of laravel ip address using get location. you can easy to get location useing ip address in laravel.In this example, I will useing stevebauman/location packege get location useing ip address in laravel.

Many time you will need to get visitor's details for security, spam prevention etc. It's very easy to get visitor ip address and their location in PHP Laravel.

Step 1: Install stevebauman/location

Now, We will install stevebauman/location package using below command.Require this package with composer. It is recommended to only require the package for development.

composer require stevebauman/location
Step 2: Add providers and aliases

In this step,We will add below providers and aliases in the "config/app.php" file.

config/app.php
'providers' => [
  ....
  Stevebauman\Location\LocationServiceProvider::class,
],
'aliases' => [
  ....
  'Location' => Stevebauman\Location\Facades\Location::class,
]
Step 3:config with the publish command

In this step,I will publish Stevebauman\Location\LocationServiceProvider package follwing command.

php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"
Step 4: Route routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LocationController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('location',[LocationController::class,'index']);
Step 5:Controller : app/Http/Controllers/LocationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class LocationController extends Controller
{
  public function index(Request $request)
    {
      $ip= $request->ip();
      $data = \Location::get($ip);
      dd($data);
    }
}

Now we are ready to run our form laravel,laravel ip address using get location example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/location

You will see layout as like bellow:

OutPut
Stevebauman\Location\Position {#1479 
  +ip: "43.241.145.109"
  +countryName: "India"
  +countryCode: "IN"
  +regionCode: "GJ"
  +regionName: "Gujarat"
  +cityName: "Rajkot"
  +zipCode: "360004"
  +isoCode: null
  +postalCode: null
  +latitude: "22.2916"
  +longitude: "70.7932"
  +metroCode: null
  +areaCode: "GJ"
  +driver: "Stevebauman\Location\Drivers\IpApi"
}
It will help you....

React Native Flexbox Tutorial With Example

React Native Flexbox Example

Hi Dev,

Today, I will learn you how to create flexbox in react native. You can easily create flexbox in react native. First i will import namespace View, after I will make flexbox using View tag in react native.

Here, I will give you full example for simply display flexbox using react native as bellow.

Step 1 - Create project

In the first step Run the following command for create project.

expo init flexbox 
Step 2 - App.js

In this step, You will open App.js file and put the code.

import React, { Component } from 'react'
import { View, StyleSheet } from 'react-native'

const Home = (props) => {
   return (
      <View style = {styles.container}>
         <View style = {styles.redbox} />
         <View style = {styles.greenbox} />
         <View style = {styles.corolbox} />
         <View style = {styles.purplebox} />
      </View>
   )
}

export default Home

const styles = StyleSheet.create ({
   container: {
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
      paddingTop: 130
   },
   redbox: {
      width: 100,
      height: 100,
      backgroundColor: 'red'
   },
   corolbox: {
      width: 100,
      height: 100,
      backgroundColor: '#ff7f50'
   },
   greenbox: {
      width: 100,
      height: 100,
      backgroundColor: 'green'
   },
   purplebox: {
      width: 100,
      height: 100,
      backgroundColor: 'purple'
   }
})
Step 3 - Run project

In the last step run your project using bellow command.

expo start
It will help you...

Laravel Soft Delete Example Tutorial

Laravel Soft Delete Example Tutorial

Hi Guys,

Today , I will learn how to utilize soft efface in laravel,we are tell simple example of laravel soft expunge.it will laravel soft efface migration.we abstract row from database when efface record from site. But laravel introduce SoftDeletes in models that way we can't abstract from database but if abstract record from front side then it doesn't show record on front. So we can retrieve record from database if we abstract erroneous row.

How work soft efface, laravel integrate expunged_at column on the table that be default will be null and when we abstract then it will place current timestamp, Laravel Model always fetch that record have only expunged_at = null.

So, how to utilize in our project, so first when you engender table moigration then you have to integrate softDeletes(). you can optically discern like bellow example of migration.

Here i bellow example you can learn soft efface in laravel

Create Post Migration Soft Delete

In this post migration open Post migration file and put the below same code.

Path: /database/migrations/2020_01_02_095534_create_posts_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('body');
            $table->softDeletes();
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
Create Post Model Soft Delete

Next, go to app/Post.php and open post model file and put the below same code.

Now you can find deleted_at column in your post table and you have also model should look like as bellow

here following path of model fille

Path:/app/Post.php
<?php
namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;

    protected $fillable = ['title','body'];

    /**
    * The attributes that should be mutated to dates.
    *
    * @var array
    */
    protected $dates = ['deleted_at'];
}
Get All Records

Now, you can use Post model as normally like you use before, you get all record like this way.

$data = Post::get();
Delete one Record

It will return all record that have deleted_at = null only and you can also remove record like this way:

$data = Post::find(1)->delete();
Get All Records After Delete one Record

Now, you can use Post model as normally like you use before, you get all record After Delete one Record like this way.

$data = Post::withTrashed()->get();

You can check the table records.

It will help you..

Bootstrap Datetimepicker Disable Weekends Example

Bootstrap Datetimepicker Disable Weekends Example

Bootstrap Datetimepicker Disable Weekends Example

Hi Dev,

Today,i will learn you simple example of Bootstrap datetimepicker disable weekends.you can disable bootstrap datetimepicker using daysOfWeekDisabled method.we are disabled bootstrap datetimepicker in weekends.it will useing daysOfWeekDisabled options to disable weekends in bootstrap datetimepicker.

Here following example of bootstrap datetimepicker disable weekends.

Solution
    $(function () {
        $('#datetimepicker1').datetimepicker({
            daysOfWeekDisabled: [0,6]
        });
    });
Example
<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap Datetimepicker Disable Weekends Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
</head>
<body style="background:#e2e2e2;">
<div class="container">
    <h2>Bootstrap Datetimepicker Disable Weekends Example - nicesnippets.com</h2>
    <div class="row">
        <div class='col-sm-6'>
            <div class="form-group">
                <div class='input-group date' id='datetimepicker1'>
                    <input type='text' class="form-control" />
                    <span class="input-group-addon">
                        <span class="glyphicon glyphicon-calendar"></span>
                    </span>
                </div>
            </div>
        </div>
        <script type="text/javascript">
            $(function () {
                $('#datetimepicker1').datetimepicker({
                    daysOfWeekDisabled: [0,6]
                });
            });
        </script>
    </div>
</div>
</body>
</html>

It will help you..

PHP Highcharts Column Chart Example

PHP Highcharts Column Chart Example

PHP Highcharts Column Chart Example

Hi Dev,

In this blog,I will learn you how to implement simple dynamic column highcharts utilizing php mysql database.We will show example of php highcharts column chart.Highcharts is a one type js library, that provide to populate bar chart, line chart, area chart, column chart etc. Highcharts library additionally provide several theme and graphic design that way you can make better layout. Highcharts is a very popular and simple library for php developer.

Here, I will give you full example for simply exhibit highcharts column chart utilizing php as bellow.

Step 1: Create Database

In first step we require to create new database "phpexample", Or you can rename as you like. After creating successfully database, In this example we will show compare column chart of viewer and clicks, So we require to create tables. we require following two tables.

1)test_viewer

2)test_click

In this step two table by following mysql query as like bellow example.

Create test_viewer table
CREATE TABLE IF NOT EXISTS `test_viewer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `numberofview` int(11) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
Create test_click table:
CREATE TABLE IF NOT EXISTS `test_click` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `numberofclick` int(12) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

Now we require to some dummy data with different year, So you can add like added bellow screen shot, I added both tables with some dummy records that way you can simply add in yout database for testing.

test_viewer table
PHP Highcharts Column Chart Example
test_click table:
PHP Highcharts Column Chart Example
Step 2: Create Database Configuration File

Now this step, I need to create on mysql database configuration file. In this file we will add details of phpmyadmin username, password and database name, So let's create new file "db_config.php" and put bellow code.

<?php
    $dbHost = "localhost";
    $dbDatabase = "phpexample";
    $dbUser = "root";
    $dbPasswrod = "root";

    $mysqli = mysqli_connect($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
?>
Step 3: Create index.php File

Here this last step, we have to just create index.php file in root folder. In this file i write code of getting data from mysql database and convert into json data. So let's create new file "index.php" and put bellow code.

<?php
    require('db_config.php');

    /* Getting test_viewer table data */
    $sql = "SELECT SUM(numberofview) as count FROM test_viewer 
            GROUP BY YEAR(created_at) ORDER BY created_at";
    $viewer = mysqli_query($mysqli,$sql);
    $viewer = mysqli_fetch_all($viewer,MYSQLI_ASSOC);
    $viewer = json_encode(array_column($viewer, 'count'),JSON_NUMERIC_CHECK);

    /* Getting test_click table data */
    $sql = "SELECT SUM(numberofclick) as count FROM test_click 
            GROUP BY YEAR(created_at) ORDER BY created_at";
    $click = mysqli_query($mysqli,$sql);
    $click = mysqli_fetch_all($click,MYSQLI_ASSOC);
    $click = json_encode(array_column($click, 'count'),JSON_NUMERIC_CHECK);

?>
<!DOCTYPE html>
<html>
<head>
    <title>HighChart</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
    <script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<script type="text/javascript">
$(function () { 
    var data_click = <?php echo $click; ?>;
    var data_viewer = <?php echo $viewer; ?>;
    $('#container').highcharts({
        chart: {
            type: 'column'
        },
        title: {
            text: 'Yearly Website Ratio'
        },
        xAxis: {
            categories: ['2013','2014','2015', '2016']
        },
        yAxis: {
            title: {
                text: 'Rate'
            }
        },
        series: [{
            name: 'Click',
            data: data_click
        }, {
            name: 'View',
            data: data_viewer
        }]
    });
});
</script>
<div class="container">
    <br/>
    <h2 class="text-center">Highcharts php mysql json example</h2>
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>
                <div class="panel-body">
                    <div id="container"></div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
now we are ready to run this example, so just run bellow command on root folder for run your project.
php -S localhost:8000
Now you can open bellow url on your browser:
http://localhost:8000

It will help you....

Laravel 8 Toastr Notifications using yoeunes/toastr package Tutorial

Laravel 8 Toastr Notifications using yoeunes/toastr package Tutorial

Laravel 8 Toastr Notifications using yoeunes/toastr package Example

Hi Guys

Today, I will learn with you how to install and use toastr notifications using yoeunes/toastr package in laravel application.we will use yoeunes/toastr package.we will write step be step tutorial for laravel toastr notifications.

Toastr notifications yoeunes/toastr package provides warning,success,error and info notifications.You have to just follow few step for implement toastr notifications in your laravel application. In this example i give you example from scratch. So just follow bellow step.

Step 1: Install yoeunes/toastr package

We need to install yoeunes/toastr composer package for datatable, so you can install using following command:

composer require yoeunes/toastr

After that you need to set providers and alias.

config/app.php
'providers' => [
    ...
    Yoeunes\Toastr\ToastrServiceProvider::class
    ...
];

As optional if you want to modify the default configuration, you can publish the configuration file:

php artisan vendor:publish --provider='Yoeunes\Toastr\ToastrServiceProvider' Step 2: Create Route

In this is step we need to create route for datatables layout file and another one for getting data. so open your routes/web.php file and add following route.

routes/web.php
<?php
use App\Http\Controllers\HomeController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('home',[HomeController::class,'index'])->name('home');
Step 5: Create Controller

In this step, now we should create new controller as HomeController. this controller will manage layout and getting data request and return response, so put bellow content in controller file:

app/Http/Controllers/HomeController.php Success Toastr Notifications For Controller Code
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function index()
    {
        toastr()->success('Success Message');
        return view('home');
    }
}
Error Toastr Notifications For Controller Code
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function index()
    {
        toastr()->error('Error Message');
        return view('home');
    }
}
Info Toastr Notifications For Controller Code
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function index()
    {
        toastr()->info('Info Message');
        return view('home');
    }
}
Warning Toastr Notifications For Controller Code
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function index()
    {
        toastr()->warning('Warning Message');
        return view('home');
    }
}
Step 3: Create View

In Last step, let's create users.blade.php(resources/views/home.blade.php) for layout and we will write design code here and put following code:

resources/views/home.blade.php
<!DOCTYPE html>
<html>
<head>
   <title>Laravel Toastr Notifications using yoeunes/toastr package</title>
   <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css">
   @toastr_css
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3 mt-5">
            <div class="card">
                <div class="card-header text-center ">
                    Laravel Toastr Notifications using yoeunes/toastr package  - nicesnippets.com
                </div>
                <div class="card-body text-center p-5">
                    Check For Toastr Notification
                </div>
            </div>
        </div>
    </div>
</div>
</body>
@jquery
@toastr_js
@toastr_render
</html>

Now, we are ready to check, so let's check...

It will help you...

Laravel Disable Register URL Example

Laravel Disable Register URL Example

Laravel Disable Register URL Example

Hi Guys

Today, I will learn to how to disable registration route in laravel. We can also register remove Authentication Routes from route file.i will disable register create custom route in laravel.

We will used register for default Auth::routes() in my web.php file. I Will used to auth remove register routes from route file.you can easy to disable register.

Here the following example of disable register

Example: 1

Now this example in register false for add in auth route in create in web.php('routes/web.php') file.

following path:/routes/web.php
Auth::routes(['register' => false]);
Example: 2

Here this example in register disable for add in custom route in create in web.php('routes/web.php') file.

following path:/routes/web.php
// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');

// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset')->name('password.update');

// Email Verification Routes...
Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
Route::get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify');
Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');

It will help you...

Laravel Cron Job Task Scheduling Example

Laravel Cron Job Task Scheduling Example

Laravel Cron Job Task Scheduling Example

Hi Dev

In this blog, I will learn how to create Cron Job Task Scheduling in laravel we will give you simple example of cron job task scheduling with laravel. we will create example step by step of cron job using laravel task scheduling.

You can easy create a cron job task scheduling in laravel.Why we have to use cron job? and what is benefit to use cron jobs in laravel and how to setup cron job in laravel?, If you have this question then i will explain why.Many times we need to send notifications or send email automatically to users for update property or items. So at that time you can define some basic logic for each days, hours etc can run and send email notification.

Here blow the example of cron job task scheduling

Step 1 : Install Laravel Application

we are going from scratch, So we require to get fresh Laravel 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 Create New Command

Here this step, we need to create our custom command. custom command will execute with task scheduling scron job. so, let's run bellow command to create new custom command.

php artisan make:command DemoCron --command=demo:cron

After make some changes on Command file.

following path: .app/Console/Commands/DemoCron.php
<?php
   
namespace App\Console\Commands;
   
use Illuminate\Console\Command;
   
class DemoCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'demo:cron';
    
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';
    
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
    
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        \Log::info("Cron is working fine!");
     
        /*
           Write your database logic we bellow:
           Item::create(['name'=>'hello new']);
        */
      
        $this->info('Demo:Cron Cummand Run successfully!');
    }
}
Step 3: Register as Task Scheduler

Now this step, we need to define our commands on Kernel.php file with time when you want to run your command like as bellow functions

->everyMinute(); Run the task every minute
->everyFiveMinutes(); Run the task every five minutes
->everyTenMinutes(); Run the task every ten minutes
->everyFifteenMinutes(); Run the task every fifteen minutes
->everyThirtyMinutes(); Run the task every thirty minutes
->hourly(); Run the task every hour
->hourlyAt(17); Run the task every hour at 17 mins past the hour
->daily(); Run the task every day at midnight
->dailyAt(’13:00′); Run the task every day at 13:00
->twiceDaily(1, 13); Run the task daily at 1:00 & 13:00
->weekly(); Run the task every week
->weeklyOn(1, ‘8:00’); Run the task every week on Tuesday at 8:00
->monthly(); Run the task every month
->monthlyOn(4, ’15:00′); Run the task every month on the 4th at 15:00
->quarterly(); Run the task every quarter
->yearly(); Run the task every year
->timezone(‘America/New_York’); Set the timezone
following path: /app/Console/Kernel.php
<?php
   
namespace App\Console;
    
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
    
class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\DemoCron::class,
    ];
     
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('demo:cron')
                 ->everyMinute();
    }
     
    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');
     
        require base_path('routes/console.php');
    }
}
Step 4: Run Scheduler Command For Test

Here we are ready to run our cron, so you can manually check using following command of your cron. so let's run bellow command

php artisan schedule:run

Next run above command, you can check log file where we already print some text. so open you your log file it looks like as bellow:

following path: /storage/logs/laravel.php
[2021-05-18 03:46:42] local.INFO: Cron is working fine!  
[2021-05-18 03:46:52] local.INFO: Cron is working fine!  
[2021-05-18 03:46:55] local.INFO: Cron is working fine!

At last you can manage this command on scheduling task, you have to add a single entry to your server’s crontab file:

* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1
OR
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

It will help you...

Laravel Get Base URL in Controller Example

Laravel Get Base URL in Controller

Hi Dev,

Today, I will learn to you how to create laravel get base url in the controller, we will create get base url in the controller. We will show a step by step simple get base url in laravel.

You may use the url or fullurl methods to get base url in the controller. the url method will return the url without the query string, while the full url method includes the query string using get base url in the controller. you can get using url facade methods to get base url in the controller.

Here examples following different types to get base url in the controller.

Example: 1 Now In this example url() method to get url in controller
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
    $url  = url()->full();
    print_r($url);
}
Example: 2 Now in this example in request facade of url method using get url in controller
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
    $url  = \Request::url();
    print_r($url);
}
Example: 3 Here in this example in request facade of fullUrl method using get url in controller
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
    $url  = \Request::fullUrl();
    print_r($url);
}
Example: 4 Now In this example in url facade of current method using get url in controller
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
    $url  = \URL::current();
    print_r($url);
}
It will help you...

Youtube Videos Download Source code

Youtube Videos Download Source code

Hi Guys,

Today,I will expound you how to download youtube videos source code.,I will show example of download youtube videos from source code, you can videos youtube video.you can easyliy youtube video download source code .I will download youtube videos in any formate useing loader api.

Here, I will give you full example for simply Youtube Videos Download Script code in loader.to api as bellow.

Example
<!DOCTYPE html>
<html>
<head>
  <title>Youtube Videos Download Script code</title>
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
  <div class="col-md-6 offset-md-3 mt-5">
    <div class="card">
      <div class="card-header bg-info">
        <h5>Youtube Videos Download Any Online Videos</h5>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-12">
            <div class="form-group">
              <label class="text-weight"><b>Online Videos Link:</b></label>
              <input type="txt" name="link" class="form-control link" required>
            </div>
          </div>
        </div>
        <form class="form-download">
          <div class="row">
            <div class="col-md-12">
              <div class="form-group">
                <label class="text-weight"><b>Select Video Fromate:</b></label>
                <select class="form-control formte" required>
                  <option selected disabled>Select Video Formate</option>
                  <option value="mp3">Mp3</option>
                  <option value="mp4a">144 Mp4</option>
                  <option value="360">360 Mp4</option>
                  <option value="480">480 Mp4</option>
                  <option value="720">720 Mp4</option>
                  <option value="1080">1080 Mp4</option>
                  <option value="4k">4k Mp4</option>
                  <option value="8k">8k Mp4</option>
                </select>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-md-12">
              <div class="form-group mt-4 download-video">
                <button class="btn btn-success btn-block click-btn-down" type="submit">Click Me</button>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</body>
<script type="text/javascript">
  $(".click-btn-down").click(function(){
      var link = $(".link").val();
    var fromate = $(".formte").children("option:selected").val();
    var src =""+link+"="+fromate+"";
    downloadVideo(link,fromate);
  });
  function downloadVideo(link,fromate) {
      $('.download-video').html('<iframe style="width:100%;height:60px;border:0;overflow:hidden;" scrolling="no" src="https://loader.to/api/button/?url='+link+'&f='+fromate+'"></iframe>');
  }
</script>
</html>

It will help you..

Laravel 8 Resource Routing Example

Laravel 8 Resource Routing Example

Hi Dev,

Today,I will explicate you how to engender resource route in laravel 8. we will show laravel 8 resource routing example.laravel resource routing assigns the typical "crud" routes to a controller with a single line of code. for example, you may wish to engender a controller that handles all http requests for "posts" stored by your application. utilizing the composition:controller artisan command, you can expeditiously engender such a controller.

You have to engender resource route on laravel they provide insert, update, view, efface routes and second you have to engender resource controller that will provide method for insert, update, view and efface.

Here ,I will engender a controller at app/Http/Controllers/PostController.php. The controller will contain a method for each of the available resource operations.

So, in this example we will visually perceive how to engender resource route and how they work.

we have to understand why we choose resource route instead of different route. we always declare different different route for our crud application like as bellow:

<?php
use App\Http\Controllers\PostController;

Route::get('posts', '[PostController::class, 'index']');
Route::get('posts/create', '[PostController::class, 'create']');
Route::post('posts', '[PostController::class, 'store']');
Route::get('posts/{post}/edit', '[PostController::class, 'edit']');
Route::put('posts/{post}', '[PostController::class, 'update']');
Route::get('posts/{post}', '[PostController::class, 'show']');
Route::delete('posts/{post}', '[PostController::class, 'destroy']');

As you can see above route declare, we have to create six routes for our crud application module. But we can simply create those six routes by using bellow resource route:

Here, you may register a resourceful route to the controller:

Resource Route: routes/web.php
use App\Http\Controllers\PostController;
Route::resource('posts', PostController::class);
Now, you can run bellow command and check create route lists:
php artisan route:list --name=posts
Now we have output as like bellow created route:
+--------+-----------+-------------------+---------------+---------------------------------------------+--------------+
| Domain | Method    | URI               | Name          | Action                                      | Middleware   |
+--------+-----------+-------------------+---------------+---------------------------------------------+--------------+
|        | GET|HEAD  | api/user          |               | Closure                                     | api,auth:api |
|        | GET|HEAD  | posts             | posts.index   | App\Http\Controllers\PostController@index   | web          |
|        | POST      | posts             | posts.store   | App\Http\Controllers\PostController@store   | web          |
|        | GET|HEAD  | posts/create      | posts.create  | App\Http\Controllers\PostController@create  | web          |
|        | GET|HEAD  | posts/{post}      | posts.show    | App\Http\Controllers\PostController@show    | web          |
|        | PUT|PATCH | posts/{post}      | posts.update  | App\Http\Controllers\PostController@update  | web          |
|        | DELETE    | posts/{post}      | posts.destroy | App\Http\Controllers\PostController@destroy | web          |
|        | GET|HEAD  | posts/{post}/edit | posts.edit    | App\Http\Controllers\PostController@edit    | web          |
+--------+-----------+-------------------+---------------+---------------------------------------------+--------------+

I will make:controller Artisan command, we can quickly create such a controller:

Resource Controller Command:
php artisan make:controller PostController --resource

Here you can see your PostController with following resource method, So let's open and see.

app/Http/Controllers/PostController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

this way you can simply use resource route and controller, make quick crud module for your project.

It Will help you...

Laravel date_format Validation Example

Laravel date_format Validation Example
Hi Guys,

In this tutorial I will show laravel Date Format Validation example You can validate date_format validation rules. With date_format:format method you can set the preferred date format, and the filed value must match the given format.

The field under validation must match the given format. You should use either date_format when validating a field, not both. This validation rule supports all formats supported by PHP's Date class.

Example
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function store(Request $request)
{
    $request->validate([
        'start_date' => 'date_format:d/m/Y',
        'end_date' => 'date_format:d/m/Y'
    ]);
}
OR
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function store(Request $request)
{
  $request->validate([
      'start_date' => 'date_format:Y-m-d',
      'end_date' => 'date_format:Y-m-d'
  ]);
}

It will help you ...

Laravel Guzzle Request Example

Laravel Guzzle Request Example

Hi Guys

Today, I will explain how to use laravel guzzle http client request? we will show example of guzzle http client request in laravel. we will guide you how to use guzzle http client GET and POST request with php laravel.

I will use guzzlehttp/guzzle composer package for guzzle http request in laravel application.we will install the guzzlehttp/guzzle package in laravel.

A Guzzle is a PHP HTTP client that makes it easy to send HTTP requests with data, headers and trivial to integrate with web services. Guzzle is a simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc.

Here following the step and you can get simple example of guzzle.

Install Guzzle Package

In this step, we will install guzzlehttp/guzzle package and then we can easily use thir method So let's just run bellow command.

composer require guzzlehttp/guzzle
Example of Requests Using Guzzle:

Here this step, I will show you how to run all above listed request you can use following controller method:

GET Request:
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function guzzleGetRequest()
{
    $client = new \GuzzleHttp\Client();
    $request = $client->get('http://ourexample.com');
    $response = $request->getBody();
   
    dd($response);
}
Post Request:
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function guzzlePostRequest()
{
    $client = new \GuzzleHttp\Client();
    $url = "http://ourexample.com/api/blog";
   
    $myBody['name'] = "Demo";
    $request = $client->post($url,  ['body'=>$myBody]);
    $response = $request->send();
  
}
Put Request:
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function guzzlePutRequest()
{
    $client = new \GuzzleHttp\Client();
    $url = "http://ourexample.com/api/blog/1";
    $myBody['name'] = "Demo";
    $request = $client->put($url,  ['body'=>$myBody]);
    $response = $request->send();
   
    dd($response);
}
Delete Request:
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function guzzleDeleteRequest()
{
    $client = new \GuzzleHttp\Client();
    $url = "http://ourexample.com/api/blog/1";
    $request = $client->delete($url);
    $response = $request->send();

    dd($response);
}

It will help you...