Laravel 8 Spatie Medialibrary Example

Laravel Spatie Medialibrary

Hi Guys,

Nowadays, I can study you the way to use spatie medialibrary in laravel 8 application,we are able to show example of laravel spatie medialibrary.you can easliy use spatie media library laravel eight.this package use to add a image or an avatar. in this academic we will show you an smooth manner to feature it, using Spatie’s Media Library bundle.

In this post, let’s move over the well-known laravel medialibrary package deal evolved by way of Spatie. This bundle deal can accomplice all sorts of documents together with your Eloquent models.

Here, I'm able to give you full example for spatie media library laravel eight as bellow.

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 post
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(post)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3 : Install Spatie Medialibrary

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

composer require "spatie/laravel-medialibrary:^9.6.0"

After the package is installed, run the following command to copy the migration file from to package directory to your project directory and also to run the fresh migration command.

php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="migrations"

php artisan migrate
Step 4: Create Model and Migration

here this step, we will create one model and migration name post. Use the below following command and create it

php artisan make:model post -m

Next,Open post migration file and put the below code. here following path of migration file

Path: /database/migrations/2020_05_27_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->id();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

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

Next, go to app/post.php and open post model file and put the below code. here following path of model fille

Path:/app/Models/Post.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Post extends Model implements HasMedia
{
    use HasFactory,InteractsWithMedia;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'body',
    ];
}
Step 5: Create Route

Create two routes one for show form and the second route send data to the server:

here following path of route fille

Path:/routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

/*
|--------------------------------------------------------------------------
| 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('post',[PostController::class,'index'])->name('post');
Route::get('post/create',[PostController::class,'create'])->name('post.create');
Route::post('post/store',[PostController::class,'store'])->name('post.store');
Step 6:Create Controller

In this step,we will create a controller. Use the below command for generate controller

php artisan make:controller PostController 

Here this step,we will create two methods inside the controller first index method is used to display post form and second store method is used to store data in the mysql database and image upload Medialibrary to storge folder

here following path of Controller fille.

Path:/app/Http/Controllers/postController.php
<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {    
        $posts = Post::latest()->get();

        return view('post.index',compact('posts'));
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $input = $request->all();

        $post = Post::create($input);

        if($request->hasFile('image') && $request->file('image')->isValid()){
            $post->addMediaFromRequest('image')->toMediaCollection('images');
        }

        return redirect()->route('post');
    }
}
Step 7:Create a blade view

In this step, we will create two blade file name post/index.blade.php and post/create.blade.php.

here following path of index.blade fille

Path:/resources/views/post/index.blade.php

<html>
<head>
    <title>Laravel Spatie Medialibrary Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" />
</head>
<body class="bg-dark">
<div class="container">
    <div class="row">
        <div class="col-md-8 offset-2">
            <div class="card mt-5">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-10">
                            <h5>Laravel 8 Spatie Medialibrary Example</h5>
                        </div>
                        <div class="col-md-2 text-center">
                            <a href="{{ route('post.create') }}" class="btn btn-success btn-sm">Create</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Title</th>
                                <th width="25%">Image</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($posts as $key=>$post)
                                <tr>
                                    <td>{{ ++$key }}</td>
                                    <td>{{ $post->title }}</td>
                                    <td><img src="{{$post->getFirstMediaUrl('images', 'thumb')}}" / width="100%"></td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Next following path create a create.blade fille

Path:/resources/views/post/create.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Spatie Medialibrary Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" />
</head>
<body class="bg-dark">
<div class="container">
    <div class="row">
        <div class="col-md-8 offset-2">
            <div class="card mt-5">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-10">
                            <h5>Laravel 8 Spatie Medialibrary Example</h5>
                        </div>
                        <div class="col-md-2 text-center">
                            <a href="{{ route('post') }}" class="btn btn-info btn-sm">Back</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <form action="{{ route('post.store') }}" method="post" enctype="multipart/form-data">
                        @csrf
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <div class="form-group">
                                    <label for="">Title:</label>
                                    <input type="" name="title" class="form-control" placeholder="Enter Title">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label for="">Body:</label>
                                <textarea name="body" id="" class="form-control" rows="3"></textarea>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label for="">Image:</label>
                                <input type="file" name="image" class="form-control">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3 text-center">
                                <button class="btn btn-success btn-block">Submit</button>
                            </div>
                        </div>    
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

After Note that to view the files in the browser you need to make the files public that is stored in the storage directory, you need to run the following command on your project root in terminal/command-line.

php artisan storage:link
next change .env file in APP_URL path
......
APP_URL=http://localhost:9000
......

Now, we will use the php artisan serve command.

php artisan serve --port=9000

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

http://localhost:9000/post

It will help you...

Laravel Select2 Ajax Autocomplete Example

Hi Dev,

Nowadays, I will create auto whole the use of Select2 and Ajax in laravel. we are able to show automobile whole the use of select2.js in laravel. you can easyli create auto whole the usage of select2 and ajax in laravel.

I will give you full example of select2 ajax in laravel.

Step 1 : Install Laravel 7 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
Database Configuration

In this step, we require to make database configuration, you have to add following details on your .env file.

1.Database Username

2.Database Password

3.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:

.env
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 2: Create product Table and Model

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

php artisan make:model Product -m

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

/database/migrations/2020_03_05_100722_create_product_table.php
<?php

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

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}
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 product table. /app/Product.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
     protected $fillable = [
        'name', 'price',
    ];
}
Step 3: Create Route

now, we need to add resource route for select2 crud operations in laravel application. so open your "routes/web.php" file and add following route.

/routes/web.php
Route::get('select2', 'Select2AutocompleteController@index');
Route::get('/select2-autocomplete-ajax', 'Select2AutocompleteController@dataAjax');
Step 4: Create Controller

here this step now we should create new controller as Select2AutocompleteController. So run bellow command and create new controller.

php artisan make:controller Select2AutocompleteController

In this controller will create two methods by default as bellow methods:

1)index()

2)dataAjax()

So, let's copy bellow code and put on ItemController.php file.

/app/Http/Controllers/Select2AutocompleteController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;

class Select2AutocompleteController extends Controller
{
    /**
    * Show the application layout.
    *
    * @return \Illuminate\Http\Response
    */
    public function index()
    {
    	return view('select2.index');
    }
    
    /**
    * Show the application dataAjax.
    *
    * @return \Illuminate\Http\Response
    */
    public function dataAjax(Request $request)
    {
    	$data = [];

        if($request->has('q')){
            $search = $request->q;
            $data =Product::select("id","name")
            		->where('name','LIKE',"%$search%")
            		->get();
        }
        return response()->json($data);
    }
}
Step 5:Create View

In last step. In this step we have to create just blade files. So mainly we have to create layout file and then create new folder "select2" then create blade files of crud app. So finally you have to create following bellow blade file:

here create following file and put bellow code.

/resources/views/select2/index.blade.php
<!DOCTYPE html>
<html>
<head>
  <title>Laravel - Dynamic autocomplete search using select2 JS Ajax</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 src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body class="bg-dark">
<div class="container mt-4">
  <div class="row">
    <div class="col-md-8 offset-md-2">
      <div class="card">
        <div class="card-header">
          <h4>Laravel - Dynamic autocomplete search using select2 JS Ajax</h4>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-12">
              <select class="itemName form-control" name="itemName"></select>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
<script type="text/javascript">
$('.itemName').select2({
  placeholder: 'Select an item',
  ajax: {
    url: '/select2-autocomplete-ajax',
    dataType: 'json',
    delay: 250,
    processResults: function (data) {
      return {
        results:  $.map(data, function (item) {
              return {
                  text: item.name,
                  id: item.id
              }
          })
      };
    },
    cache: true
  }
});
</script>
</html>
Now we are ready to run our example so run bellow command for quick run:
php artisan serve
Now you can open bellow URL on your browser:
http://localhost:8000/select2

It will help you...

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...