Showing posts sorted by relevance for query laravel. Sort by date Show all posts
Showing posts sorted by relevance for query laravel. Sort by date Show all posts

Laravel 8 Auth using Jetstream Example

Laravel 8 Auth using Jetstream Example

Hi Dev,

Today, I will show you laravel 8 authentication using jetstream. In this blog, I will give you simple example of laravel 8 auth with jetstream. you can see jetstream with auth in laravel 8 application. i would like to share with you laravel 8 jetstream auth with inertia.

Few days ago laravel 8 realeased and they provides lot's of new updates. laravel 7 was using laravel/ui for auth scaffolding and now laravel 8 provide jetstream for login, registration, email verification, two-factor authentication, session management, API support and team management.

Laravel 8 designed by Tailwind CSS and they provide auth using livewire and Inertia. i will show you how to add auth in laravel 8. you can easily create laravel auth with jetstream step by step.

Here I will give full example for jetstream with auth in laravel 8, So let's follow bellow step by step.

Laravel 8 Auth Scaffolding using Livewire Jetstream

Laravel Livewire is a library that makes it simple to build modern, reactive, dynamic interfaces using Laravel Blade, Laravel controller and Laravel validation.

Livewire provide way to write your ajax with laravel blade, validation and all, you can use as javascript framework. so let's see bellow step to create auth using laravel 8 livewire.

Install Laravel 8:

Here you can install laravel 8 application using bellow command to get laravel 8:

composer create-project --prefer-dist laravel/laravel blog
Install Jetstream:

Now, you can install jetstream using bellow command so lets open terminal and run bellow command:

composer require laravel/jetstream
Create Auth with Livewire:

Now we need to create authentication using bellow command you can create basic login, register and email verification. if you want to create team management then you have to pass addition parameter. you can see bellow commands:

php artisan jetstream:install livewire
  
OR
  
php artisan jetstream:install livewire --teams

Now, let's node js package:

npm install

let's run package:

npm run dev

Now, we have to need migration so let's bellow artisan command to migrate database:

php artisan migrate

Now, you can run and check. they installed all views, actions and all in your laravel 8 application.

Laravel 8 Auth Scaffolding using Inertia Jetstream

Laravel Inertia is a templating language and Inertia is working with vue js.

Install Laravel 8:

Here you can install laravel 8 application using bellow command to get laravel 8:

composer create-project --prefer-dist laravel/laravel blog
Install Jetstream:

Now, you can install jetstream using bellow command so lets open terminal and run bellow command:

composer require laravel/jetstream
Create Auth with Inertia:

Now we need to create authentication using bellow command you can create basic login, register and email verification. if you want to create team management then you have to pass addition parameter. you can see bellow commands:

php artisan jetstream:install inertia
  
OR
  
php artisan jetstream:install inertia --teams

Now, let's node js package:

npm install

let's run package:

npm run dev

Now, we have to need migration so let's bellow artisan command to migrate database:

php artisan migrate

Now, you can run and check. they installed all views, actions and all in your laravel 8 application.

Laravel 8 Jetstream Features

Laravel 8 jetstream provides lot's of features. you can see all features in configuration file fortify.php and jetstream.php file where you can enable and disable option for that feature:

config/fortify.php
....
  
'features' => [
        Features::registration(),
        Features::resetPasswords(),
        Features::emailVerification(),
        Features::updateProfileInformation(),
        Features::updatePasswords(),
        Features::twoFactorAuthentication(),
    ],
...
config/jetstream.php
....
  
'features' => [
        Features::profilePhotos(),
        Features::api(),
        Features::teams(),
    ],
...

Now you can run your application by bellow command:

php artisan serve

It will help you...

Laravel 9 Barcode Generator Tutorial

Laravel 9 Barcode Generator Tutorial
Hi dev, In this blog, I am explain laravel 9 barcode generator tutorial with example. We will use picqer/php-barcode-generator package for generating barcode in laravel 9 application. So i will use how to generate barcode in laravel 9. You will learn how to save generate bar code in laravel 9. i will Creating a basic example of picqer/php-barcode-generator laravel php. This is a picqer/php-barcode-generator is a very composer package for generate barcode in our laravel 9 app. I can simply generate any svg, png, jpg and html image of barcode. So you can easily generate any barcode by using laravel 5, laravel 6, laravel 7 , laravel 8 and laravel 9 any version easily. So let's start following example: Install Laravel 9 This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel laravel-barcode
Install picqer/php-barcode-generator In first step we will install picqer/php-barcode-generator Package that provides to generate Barcode in laravel application. So, first open your terminal and run bellow command:
composer require picqer/php-barcode-generator
1: Laravel Generate Barcode Example Here, we will create simple route for generating Barcode, Then i will show you output bellow as well: routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
/*
|--------------------------------------------------------------------------
| 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('barcode', function () {
  
    $generatorPNG = new Picqer\Barcode\BarcodeGeneratorPNG();
    $image = $generatorPNG->getBarcode('000005263635', $generatorPNG::TYPE_CODE_128);
  
    return response($image)->header('Content-type','image/png');
});
Output:
2: Laravel Generate Barcode and Save Example Here, we will create simple route for generating Barcode: routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
/*
|--------------------------------------------------------------------------
| 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('barcode-save', function () {
  
    $generatorPNG = new Picqer\Barcode\BarcodeGeneratorPNG();
    $image = $generatorPNG->getBarcode('000005263635', $generatorPNG::TYPE_CODE_128);
  
    Storage::put('barcodes/demo.png', $image);
  
    return response($image)->header('Content-type','image/png');
});
3: Laravel Generate Barcode with Blade Example Here, we will create simple route for generating Barcode, Then i will show you output bellow as well: routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
/*
|--------------------------------------------------------------------------
| 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('barcode-blade', function () {
  
    $generatorHTML = new Picqer\Barcode\BarcodeGeneratorHTML();
    $barcode = $generatorHTML->getBarcode('0001245259636', $generatorHTML::TYPE_CODE_128);
  
    return view('barcode', compact('barcode'));
});
resources/views/barcode.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>laravel 9 barcode generator tutorial with example - Itwebtuts</title>
</head>
<body>
    
    <h1>laravel 9 barcode generator tutorial with example - Itwebtuts</h1>
         
    <h3>Product: 1234567890</h3>  
    {!! $barcode !!}
  
</body>
</html>
I hope it can help you...

Laravel 9 Livewire Auth Scaffolding using Jetstream Example

Laravel 9 Livewire Auth Scaffolding using Jetstream
Hi dev, Today, In this tutorial laravel 9 livewire auth scaffolding using jetstream. today you can visually perceive laravel 9 auth with livewire jetstream. we will avail you to give an example of laravel 9 auth with livewire tutorial. I learn simply step by step laravel 9 authentication livewire example. So, let's follow a few steps to engender an example of authentication laravel 9 livewire jetstream. Laravel 9 auth scaffolding example; In this tutorial, you will learn from scratch on how to build a login, register, logout, forget password, profile and reset password page by using scaffolding Jetstream without using laravel 9 make:auth command. Livewire provides a indite to your ajax with laravel blade, validation, etc. you can utilize a javascript framework. so you can visually perceive bellow step to engender auth utilizing laravel 9 livewire. So let's start by following an example. Install Laravel 9 here, we need to install laravel 9 application using composer command.
composer create-project laravel/laravel laravel-livewire-jetstream
Install Jetstream: Now, in this step, we need to use composer command to install jetstream, so let's run bellow command and install bellow library.
composer require laravel/jetstream
Create Auth with Livewire: now, we need to create authentication using bellow command. you can create basic login, register and email verification. if you want to create team management then you have to pass addition parameter. you can see bellow commands:
php artisan jetstream:install livewire
  
OR
  
php artisan jetstream:install livewire --teams
Now, let's node js package:
npm install
let's run package:
npm run dev
now, we need to run migration command to create database table:
php artisan migrate
Now, you can run and check. they installed all views, actions and all in your laravel 9 application. Laravel 9 Jetstream Features Laravel 9 Jetstream provides new all feature are configurable. you can see there is a configuration file fortify.php and jetstream.php file where you can enable and disable option for that feature: config/fortify.php
....
  
'features' => [
        Features::registration(),
        Features::resetPasswords(),
        Features::emailVerification(),
        Features::updateProfileInformation(),
        Features::updatePasswords(),
        Features::twoFactorAuthentication(),
    ],
...
config/jetstream.php
....
  
'features' => [
        Features::profilePhotos(),
        Features::api(),
        Features::teams(),
    ],
...
Run Laravel App: All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/
I hope it can help you...

Laravel 9 Yajra Datatables Example

Laravel 9 Yajra Datatables Tutorial

Hi Dev,

Today, This blog will provide some of the most important how to use yajra data tables in laravel 9?. The complete step by step guide of laravel 9 yajra datatables example. This Laravel 9 tutorial help to implement yajra data table with laravel 9. i will give you simple example of yajra data tables with ajax in laravel 9. In this example of how to use bootstrap data tables in laravel 9. Yajra DataTables is a jQuery plug-in which is helps us in Laravel for more functionalities like searching, sorting, pagination on tables. If you search how to use yajra data tables in laravel then here in this example is perfect implement from scratch. You have to just follow a few steps for implement data tables in your laravel application. let's start to use data tables in laravel application. Step 1: Install Laravel 9 This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel laravel-yajra-table
Step 2: Install Yajra Datatable In this step we need to install yajra datatable via the Composer package manager, so one your terminal and fire bellow command:
composer require yajra/laravel-datatables-oracle
Step 3: Add Dummy Users In this step, we will create some dummy users using tinker factory. so let's create dummy records using bellow command:
php artisan tinker
  
User::factory()->count(20)->create()
Step 4: Create Controller In this point, now we should create new controller as UserController. this controller will manage layout and getting data request and return response, so put bellow content in controller file: app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use DataTables;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = User::select('*');
            return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){
       
                            $btn = '<a href="javascript:void(0)" class="edit btn btn-success btn-sm text-center">View</a>';
      
                            return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
          
        return view('users');
    }
}
Step 5: Add 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 Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
/*
|--------------------------------------------------------------------------
| 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('users', [UserController::class, 'index'])->name('users.index');
Step 6: Create Blade File In Last step, let's create users.blade.php(resources/views/users.blade.php) for layout and we will write design code here and put following code: resources/views/users.blade.php
<!DOCTYPE html>
<html>
<head>
    <title> laravel 9 yajra datatables example - Itwebtuts </title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>  
    <script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.4/js/dataTables.bootstrap5.min.js"></script>
</head>
<body>
     
<div class="container">
    <h3 class="text-center mt-3 mb-4">laravel 9 yajra datatables example - Itwebtuts</h3>
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Email</th>
                <th width="100px" class="text-center">Action</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
     
</body>
     
<script type="text/javascript">
  $(function () {
      
    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('users.index') }}",
        columns: [
            {data: 'id', name: 'id'},
            {data: 'name', name: 'name'},
            {data: 'email', name: 'email'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });
      
  });
</script>
</html>
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/users
I hope it can help you...

Laravel Add Share Social Media Button Example

Laravel Add Share Social Media Button Example

Hi Dev,

Today, i would like share with you how to integrate share social media button in laravel application. We will show laravel share post on social media example. This article will give you example of how to share social media links in laravel.

If you want to share your post in social media using social button then you can use bellow example. Here i will give simple example of how to add social media share buttons on website in laravel.

Here i will give full example for laravel share post on facebook, twitter, whatsapp etc. you can also use this example with laravel 6, laravel 7 and laravel 8 version. So let's see the bellow example step by step.

Step 1: Install Laravel Project

First, you need to download the laravel fresh setup. Use this command then download laravel project setup :

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Install "jorenvanhocht/laravel-share" Package

In this step, You have to need jorenvanhocht/laravel-share package. So let's open terminal and run bellow composer command:

composer require jorenvanhocht/laravel-share

Run succefully above command then after open config/app.php and put the bellow code.

config/app.php
'aliases' => [
    'Share' => Jorenvh\Share\ShareFacade::class,
]

Now publish config file using bellow command so lets open terminal and run bellow command:

php artisan vendor:publish --provider="Jorenvh\Share\Providers\ShareServiceProvider"
Step 3 : Add Route

now, we need to add route for share social in laravel application. so open your "routes/web.php" file and add following route.

route/web.php
<?php
use App\Http\Controllers\ShareSocialController;

Route::get('/share-social', [ShareSocialController::class,'shareSocial']);
Step 4 : Create Controller

Here this step now we should create new controller as ShareSocialController. So run bellow command and create new controller.

php artisan make:controller ShareSocialController
app/http/controller/ShareSocialController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

class ShareSocialController extends Controller
{
    public function shareSocial()
    {
        $socialShare = \Share::page(
            'http://itwebtuts.blogspot.com/',
            'itwebtuts',
        )
        ->facebook()
        ->twitter()
        ->reddit()
        ->linkedin()
        ->whatsapp()
        ->telegram();
        
        return view('share-social', compact('socialShare'));
    }
}
Step 5 : Create Blade File

In last step. we have to create blade file for list of social button. So finally you have to create following file and put bellow code:

/resources/views/share-social.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>How to Add Share Social Media Button in Laravel</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js" integrity="sha512-XKa9Hemdy1Ui3KSGgJdgMyYlUg1gM+QhL6cnlyTe2qzMCYm4nAZ1PsVerQzTTXzonUR+dmswHqgJPuwCq1MaAg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" integrity="sha512-P5MgMn1jBN01asBgU0z60Qk4QxiXo86+wlFahKrsQf37c9cro517WzVSPPV1tDKzhku2iJ2FVgL67wG03SGnNA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style type="text/css">
        li{
            list-style: none;
            background: #e2e2e2;
            margin-left: 5px;
            text-align: center;
            border-radius:5px;
        }
        li span{
            font-size: 20px;
        }
        ul li{
            display: inline-block;
            padding: 10px 10px 5px;
        }
        #social-links{
            float: left;
        }
    </style>
</head>
<body class="bg-dark">
    <div class="row mt-5">
        <div class="col-md-6 offset-3">
            <div class="card">
                <div class="card-header">
                    <h5>How to Add Share Social Media Button in Laravel</h5>
                </div>
                <div class="card-body">
                    <strong class="float-left pt-2">Social Media : </strong>
                    {!! $socialShare !!}
                </div>
            </div>
        </div>
    </div>
</body>
</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/share-social

It will help you...

Laravel 9 Sweet Alert Confirm Delete Tutorial

Laravel 9 Sweet Alert Confirm Delete Tutorial
Hi dev, In this blog, I am explaining laravel 9 sweet alert confirm delete example. you'll learn laravel 9 sweet alert box using data delete in the table. if you have a question about laravel 9 sweet alert then I will give a simple example with a solution. you will do the following things for laravel 9 sweet alert using record delete. Below we use sweet alert CDN to show confirm box alert before deleting any row from laravel 9 blade file. The sweet alert in any project is very important because the confirmation delete is very required to make confirm once the user is satisfied to delete your record. So the Laravel Delete with Sweetalert has been used in all projects. In this example, we will learn how to open a sweet alert before deleting a user in laravel 9 application. I will show the sweet alert jquery plugin using delete in laravel 9. I will show an easy example of a sweet alert before deleting the user in laravel 9. Let’s Delete method with Sweet Alert in Laravel 8, Laravel 7, Laravel 6, Laravel 5 easy way step by step from scratch. Step 1: Install Laravel App In this step, You can install laravel fresh app. So open the terminal and put the bellow command.
composer create-project --prefer-dist laravel/laravel laravel-sweet-alert
Step 2: Add Dummy Users In this step, we need to create add some dummy users using factory.
php artisan tinker
    
User::factory()->count(10)->create()
Step 3: Create Route In this is step we need to create some routes for add to cart function.
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
/*
|--------------------------------------------------------------------------
| 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('users', [UserController::class, 'index'])->name('users.index');
Route::delete('users/{id}', [UserController::class, 'delete'])->name('users.delete');
Step 4: Create Controller in this step, we need to create UserController and add following code on that file: app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use DataTables;

class UserController extends Controller
{
     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $users = User::select("*")->paginate(8);
        return view('users', compact('users'))->with('no', 1);
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function delete($id)
    {
        User::find($id)->delete();
        return back();
    }
}
Step 5: Create Blade Files here, we need to create blade files for users, products and cart page. so let's create one by one files: resources/views/users.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Sweet Alert Confirm Delete Example - Itwebtuts</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/5.0.7/sweetalert2.min.css" rel="stylesheet">
</head>
<body>
      
<div class="container">

    <h3 class="text-center mt-4 mb-5">Laravel 9 Sweet Alert Confirm Delete Example - Itwebtuts</h3>
  
    <table class="table table-bordered table-striped data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Email</th>
                <th class="text-center">Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $user)
                <tr>
                    <td>{{ $no++ }}</td>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                    <td class="text-center">
                        <form method="POST" action="{{ route('users.delete', $user->id) }}">
                            @csrf
                            <input name="_method" type="hidden" value="DELETE">
                            <button type="submit" class="btn btn-xs btn-danger btn-flat show-alert-delete-box btn-sm" data-toggle="tooltip" title='Delete'>Delete</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>
</div>
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>

<script type="text/javascript">
    $('.show-alert-delete-box').click(function(event){
        var form =  $(this).closest("form");
        var name = $(this).data("name");
        event.preventDefault();
        swal({
            title: "Are you sure you want to delete this record?",
            text: "If you delete this, it will be gone forever.",
            icon: "warning",
            type: "warning",
            buttons: ["Cancel","Yes!"],
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((willDelete) => {
            if (willDelete) {
                form.submit();
            }
        });
    });
</script>

</body>
</html>
Now we are ready to run our example so run bellow command so quick run:
php artisan serve
Now you can open bellow URL on your browser:
localhost:8000/users
I hope it can help you...

Laravel Highcharts Example with Tutorial

Laravel Highcharts Example with Tutorial
Hi dev, Today,In this example, I am explain how to use highcharts in laravel 9. In this article i will show you highchart in laravel 9. We will learn how to add highchart in laravel 9. This tutorial demonstrates how to create charts in Laravel 9 with Highcharts. you will learn how to implement a highcharts in laravel 9 using highchart js.using highcharts you can create interactive charts easily for your web projects. so, now we will see basic line chart using highcharts in laravel 9. Highcharts is a modern SVG-based, multi-platform charting library. It makes it easy to add interactive charts to web and mobile projects. If you work with any web application or e-commerce application or any dating application etc, And need to show analytics on these application dashboards. So this laravel 9 highcharts example tutorial helps you, how to fetch month wise data and how to display month wise data in highcharts for analytics on laravel application. Step 1: Install Laravel 9 This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel laravel-highcharts
Step 2: Create Route first of all we will create simple route for creating simple line chart. so let's add simple routes as like bellow: routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\HighchartController;
  
/*
|--------------------------------------------------------------------------
| 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('chart', [HighchartController::class, 'index']);
Step 3: Create Controller Here, we will create new controller as HighchartController. so let's add bellow code on that controller file. app/Http/Controllers/HighchartController.php
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use DB;
  
class HighchartController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $users = User::select(DB::raw("COUNT(*) as count"))
                    ->whereYear('created_at', date('Y'))
                    ->groupBy(DB::raw("Month(created_at)"))
                    ->pluck('count');
            
        return view('chart', compact('users'));
    }
}
Step 4: Create Blade File: here, we need to create blade file and in this blade file we use highchart js and use their code. resources/views/chart.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Highcharts Example with Tutorial - Itwebtuts</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
   
<body>
<div class="col-md-12 text-center my-4">
    <h2>Laravel Highcharts Example with Tutorial - Itwebtuts</h2>
</div>
<div id="container"></div>
</body>
  
<script src="https://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
    var users =  {{ Js::from($users) }};
   
    Highcharts.chart('container', {
        title: {
            text: 'New User Growth, 2022'
        },
        subtitle: {
            text: 'Source: itsolutionstuff.com.com'
        },
         xAxis: {
            categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        },
        yAxis: {
            title: {
                text: 'Number of New Users'
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle'
        },
        plotOptions: {
            series: {
                allowPointSelect: true
            }
        },
        series: [{
            name: 'New Users',
            data: users
        }],
        responsive: {
            rules: [{
                condition: {
                    maxWidth: 500
                },
                chartOptions: {
                    legend: {
                        layout: 'horizontal',
                        align: 'center',
                        verticalAlign: 'bottom'
                    }
                }
            }]
        }
    });
</script>
</html>
Step 5: Create Dummy Records: Here, we need to add some dummy records on users table as monthly wise. you can create dummy records using laravel tinker command as bellow:
php artisan tinker
User::factory()->count(30)->create()
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/chart
I hope it can help you...

Laravel 9 Generator QR Code Tutorial

Laravel 9 Generator QR Code

Hey Dev,

Today, In this tutorial, I am explain laravel 9 generator QR code tutorial with an example. In this tutorial, we will learn how to generate/create QR code using simple-QRcode or simplesoftwareio/simple-qrcode in laravel 9 app. And as well as learn how to generate QR codes with text, size, color, background color, format like png, eps, SVG. We will learn to generate QR Code in laravel 9. The simple-qrcode package is used to generate QR codes in your laravel 9 application.

QR codes package is very easy to install and also very easy to use. A simple QR code package has provided us with many functions for generating QR codes. So following this example is how to generate QR codes. Install Laravel 9 This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel laravel-qr-code
Install simplesoftwareio/simple-qrcode In the first step, we will install simplesoftwareio/simple-qrcode Package that provides to generates QR codes in laravel application. So, first, open your terminal and run bellow command:
composer require simplesoftwareio/simple-qrcode
1: Laravel Generate QR Code Example Here, we will create a simple route for generating QR code, Then I will show you the output bellow as well: routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
/*
|--------------------------------------------------------------------------
| 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('qrcode', function () {
    return QrCode::size(300)->generate('A basic example of QR code!');
});
2: Laravel Generate QR Code and Save Example Here, we will create simple route for generating qr code: routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
/*
|--------------------------------------------------------------------------
| 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('qrcode-with-color', function () {
	$path = public_path('qrcode/'.time().'.png');
  
    return QrCode::size(300)
                ->generate('A simple example of QR code', $path);
});
3: Laravel Generate QR Code with Color Example Here, we will create a simple route for generating QR code, Then i will show you the output bellow as well: routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
/*
|--------------------------------------------------------------------------
| 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('qrcode-with-color', function () {
  
    return QrCode::size(300)
                    ->backgroundColor(255,55,0)
                    ->generate('A simple example of QR code');
});
4: Laravel Generate QR Code with Image Example Here, we will create a simple route for generating QR code, Then I will show you the output bellow as well: routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
/*
|--------------------------------------------------------------------------
| 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('qrcode-with-image', function () {
  
        $image = QrCode::format('png')
                        ->merge(public_path('images/1644463030.png'), 0.5, true)
                        ->size(500)
                        ->errorCorrection('H')
                        ->generate('A simple example of QR code!');
  
        return response($image)->header('Content-type','image/png');
});
5: Laravel Generate Email QR Code Example Here, we will create a simple route for generating QR code, Then I will show you the output bellow as well: routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
/*
|--------------------------------------------------------------------------
| 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('qrcode-email', function() {
  
    return QrCode::size(500)
                ->email('dharmik@gmail.com', 'Welcome to Itwebtuts!', 'This is !.');
 });
6: Laravel Generate Phone QR Code Example Here, You can generate qr code with phone number as below: Code:
QrCode::phoneNumber('111-222-6666');
7: Laravel Generate SMS QR Code Example Here, You can generate qr code with sms as below: Code:
QrCode::SMS('111-222-6666', 'Body of the message');
8: Laravel Generate QR Code in Blade File Example Here, You can generate OR code in blade file: Code:
<div class="visible-print text-center">
    {!! QrCode::size(100)->generate('Demo'); !!}
    <p>Scan me to return to the original page.</p>
</div>
I hope it can help you...

Laravel Inertia JS Pagination Example

Laravel Inertia JS Pagination Example

Hi Guys,

Today, I will learn you how to use inertia js pagination in laravel. We will show example of laravel inertia js pagination.if you want to see example of laravel inertiajs pagination then you are a right place. i explained simply about pagination in laravel inertia js.

We will give you step by step simple example of how to add pagination using laravel inertia js. I will use laravel breeze with inertia to creating this example.

Here, I will give you full example for inertia js pagination using Laravel 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 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 Laravel Breeze

In this step, let's install laravel breeze with inertia, So open your terminal OR command prompt and run bellow command.

composer require laravel/breeze --dev

After, install breeze with inertia and also run migration using bellow command.

php artisan breeze:install --inertia
  
npm install
  
npm run dev
  
php artisan migrate
Step 4: Create Route

In this step, we will create one route for list of all users, add users route here. So, let's add new route on that file.

routes/web.php
<?php
  
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
  
use App\Http\Controllers\UserController;
  
/*
|--------------------------------------------------------------------------
| 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('/', function () {
    return Inertia::render('Welcome', [
        'canLogin' => Route::has('login'),
        'canRegister' => Route::has('register'),
        'laravelVersion' => Application::VERSION,
        'phpVersion' => PHP_VERSION,
    ]);
});
  
Route::get('/dashboard', function () {
    return Inertia::render('Dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');
 
Route::get('users', [UserController::class, 'index']);
  
require __DIR__.'/auth.php';
Step 5: Create Controller

Here in this step, now we have create UserController with index methods, in this method we will write code of return inertia view. So let's create controller.

app/Http/Controllers/UserController.php
<?php
   
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use Inertia\Inertia;
  
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $users = User::orderBy('id', 'desc')
                        ->paginate(5);
  
        return Inertia::render('Users', [
            'users' => $users
        ]);
    }
}
Step 6: Add Page and Component

Now this step, we need to add pagination component and user vue page. let's add as bellow.

<template>
  <layout title="Users">
    <div class="container">
      <h1>Laravel Inertia JS Pagination Example - MyWebtuts.com</h1>
      <table class="table border w-full">
        <thead>
          <tr>
            <th class="border p-3">ID</th>
            <th class="border p-3">Name</th>
            <th class="border p-3">Email</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in users.data" :key="user.id">
            <td class="border p-3">{{ user.id }}</td>
            <td class="border p-3">{{ user.name }}</td>
            <td class="border p-3">{{ user.email }}</td>
          </tr>
        </tbody>
      </table>
  
      <pagination class="mt-6" :links="users.links" />
    </div>
  </layout>
</template>
  
<script>
import Pagination from '@/Components/Pagination'
  
export default {
  components: {
    Pagination
  },
  props: {
    users: Object,
  },
}
</script>
resources/js/Components/Pagination.vue
<template>
  <div v-if="links.length > 3">
    <div class="flex flex-wrap -mb-1">
      <template v-for="(link, k) in links" :key="k">
        <div v-if="link.url === null"  class="mr-1 mb-1 px-4 py-3 text-sm leading-4 text-gray-400 border rounded" v-html="link.label" />
        <inertia-link v-else class="mr-1 mb-1 px-4 py-3 text-sm leading-4 border rounded hover:bg-white focus:border-indigo-500 focus:text-indigo-500" :class="{ 'bg-blue-700 text-white': link.active }" :href="link.url" v-html="link.label" />
      </template>
    </div>
  </div>
</template>
  
<script>
export default {
  props: {
    links: Array,
  },
}
</script> 

now you can simple run bellow command:

npm run dev

Run laravel app with bellow command:

php artisan serve
Run bellow URL:
https://localhost:8000/users

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

Laravel 9 Livewire Generate New Slug Tutorial

Laravel 9 Livewire Generate New Slug
Hi Guys, Today, This example is how to livewire generate new slug in laravel 9?. We will teach you the simple and the best way on how to generate slug in the Laravel 9 application using the livewire package. This example is short code and easy way for user. This laravel livewire create slug example, we will install a brand new laravel app, install and set up the livewire plugin, then create model, view and controllers. How to Generate Slug in Laravel with Livewire Package. So let's start following example. Step 1 - Create Fresh Laravel Project
composer create-project --prefer-dist laravel/laravel Blog
Don’t forget to get inside the app’s root:
cd Blog
Insert Database Details in ENV
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password
Step 2 - Add Livewire Library in Laravel Its easy to install the livewire package into the laravel; you have to open the terminal, type command, and execute to begin the installation process.
composer require livewire/livewire
Step 3 - Add Eloquent Sluggable Package in Laravel In the further step, you have to install the eloquent sluggable package, and this library will help you generate slug in laravel. Make sure to run the following command to install the plugin.
composer require cviebrock/eloquent-sluggable
Step 4 - Publish Sluggable Config File Now laravel slug package has been installed; now, you have to register this package for starting the creation of slugs as per the laravel eloquent models. Let us execute the command to publish the configuration file in laravel.
php artisan vendor:publish --provider="Cviebrock\EloquentSluggable\ServiceProvider"
Step 5 - Create Model and Migrations Let us create a migration and model files; theoretically, these files help in creating the table into the database. Run the below command to generate a migration and model simultaneously.
php artisan make:model Blog -m
Open app/Models/Blog.php and add the values in the newly generated models file.
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

use Cviebrock\EloquentSluggable\Sluggable;

class Blog extends Model
{
    use HasFactory,Sluggable;

    protected $fillable = [
        'blog_title',
        'slug',
    ];

    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'blog_title'
            ]
        ];
    }
}
Open database/migrations/create_blogs_table.php and insert the table properties within the migration file.
<?php

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

class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('blog_title');
            $table->string('slug');            
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
}
Now, go to console, type the recommended command to run the migration.
php artisan migrate
Step 6 - Create Route in Laravel Open the routes/web.php in this file you need to define the route.
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| 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::view('/generate-slug', 'welcome');
Step 7 - Set Up Livewire Component Next, you have to execute the following command to generate the livewire blog components.
php artisan make:livewire Blogs
Eventually, the suggested command created two files on the following path:
app/Http/Livewire/Blogs.php
resources/views/livewire/blogs.blade.php
Open and update the below code in app/Http/Livewire/Blogs.php file:
<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Blog;
use \Cviebrock\EloquentSluggable\Services\SlugService;

class Blogs extends Component
{
    public $blog_title;
    public $slug;

    public function render()
    {
        $blogs = Blog::latest()->take(7)->get();
        return view('livewire.blogs', compact('blogs'));
    }

    public function generateSlug()
    {
        $this->slug = SlugService::createSlug(Blog::class, 'slug', $this->blog_title);
    }

    public function store()
    {
        Blog::create([
            'blog_title' => $this->blog_title,
            'slug'  => $this->slug
        ]);
    }    
}
Open and update the below code in resources/views/livewire/blogs.php file:
<div>
    <form wire:submit.prevent="store">
        <div class="form-group">
            <label for="blog_title" class="mb-2"><strong>Blog Title</strong></label>
            <div class="col-md-12 mb-3">
                <input wire:model="blog_title" type="text" class="form-control @error('blog_title') is-invalid @enderror" autofocus>

                @error('blog_title')
                <span class="invalid-feedback">
                    <strong>{{ $message }}</strong>
                </span>
                @enderror

            </div>
        </div>

        <div class="col-md-12">
            <div class="d-grid">
                <button type="submit" class="btn btn-dark">
                    Create Blog
                </button>
            </div>
        </div>
    </form>
    <table class="table mt-5">
        <thead>
            <tr>
                <th>Blog Title</th>
                <th>Slug</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($blogs as $blog)
            <tr>
                <td>{{ $blog->blog_title }}</td>
                <td>{{ $blog->slug }}</td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>
Step 8 - Set Up Blade View In the last step, make sure to head over to resources/views/livewire/ folder, you have to create the welcome.blade.php file in this directory and after that insert all the given below code in the suggested file: Update resources/views/livewire/welcome.blade.php file.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <title>Implement Slug in Laravel Livewire Example - Itwebtuts</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
    @livewireStyles
</head>

<body>
    <div class="container mt-3">
        @if (session()->has('message'))
        <div class="alert alert-primay">
            {{ session('message') }}
        </div>
        @endif
        @livewire('blogs')
    </div>
    @livewireScripts
</body>

</html>
Step 9 - Start Laravel App The last task is to start the laravel development server, go to terminal and run the given below command to run the app.
php artisan serve
Open your browser below url and view the app.
http://localhost:8000/generate-slug
I hope it can help you....

Laravel 8 Sanctum API Authentication Tutorial

Laravel 8 Sanctum API Authentication Tutorial

Hi Dev,

In this blog,I will learn you how to use sanctum api authenticationin laravel 8. We will Show example of sanctum api authentication in laravel 8. it's simple example of laravel 8 sanctum example. you'll learn laravel 8 sanctum rest api example. So, let's follow few step to create example of laravel 8 sanctum api token tutorial.

Laravel 8 Sanctum provides a simple authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum also allows each user of your application to generate multiple API tokens for their account.

You also want to create api for your mobile application than you can follow this tutorial for how to create rest api step by step with laravel 8 and sanctum. If you are new than don't worry about that i written tutorial step by step.

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 1: Install Laravel 8

In this step we need to install sanctum via the Composer package manager, so one your terminal and fire bellow command.

composer require laravel/sanctum

After successfully install package, we need to publish configuration file with following command:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

we require to get default migration for create new sanctum tables in our database. so let's run bellow command.

php artisan migrate

Next, we need to add middleware for sanctum api, so let's add as like bellow:

app/Http/Kernel.php
....
'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
....
Step 3: Sanctum Configuration

In this step, we have to configuration on three place model, service provider and auth config file. So you have to just following change on that file.

In model we added HasApiTokens class of Sanctum,

In auth.php, we added api auth configuration.

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\Sanctum\HasApiTokens;
  
class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
  
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
  
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}
Step 4: Add Food Table and Model

In this step, We require to create migration for posts table using Laravel 8 php artisan command, so first fire bellow command.

php artisan make:migration create_foods_table

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create Foods table.

<?php

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

class CreateFoodsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('foods', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }

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

After create migration we need to run above migration by following command:

php artisan migrate

After create "foods" table you should create Food model for foods, so first create file in this path app/Models/Food.php and put bellow content in item.php file.

app/Models/Food.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Food extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'detail'
    ];
}
Step 5: Create API Routes
<?php
  
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\API\RegisterController;
use App\Http\Controllers\API\FoodController;
  
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
  
Route::post('register', [RegisterController::class, 'register']);
Route::post('login', [RegisterController::class, 'login']);
     
Route::middleware('auth:sanctum')->group( function () {
    Route::resource('foods', FoodController::class);
});
Step 6: Create Controller Files

In this step, we have create new controller as BaseController, FoodController and RegisterController, i created new folder "API" in Controllers folder because we will make alone APIs controller, So let's create both controller.

app/Http/Controllers/API/BaseController.php
<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class BaseController extends Controller
{
    /**
    * success response method.
    *
    * @return \Illuminate\Http\Response
    */
    public function sendResponse($result, $message)
    {
    	$response = [
            'success' => true,
            'data'    => $result,
            'message' => $message,
        ];


        return response()->json($response, 200);
    }

    /**
     * return error response.
     *
     * @return \Illuminate\Http\Response
     */
    public function sendError($error, $errorMessages = [], $code = 404)
    {
    	$response = [
            'success' => false,
            'message' => $error,
        ];


        if(!empty($errorMessages)){
            $response['data'] = $errorMessages;
        }

        return response()->json($response, $code);
    }
}
app/Http/Controllers/API/RegisterController.php
<?php

namespace App\Http\Controllers\API;
use App\Http\Controllers\API\BaseController as BaseController;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Validator;

class RegisterController extends BaseController
{
     /**
     * Register api
     *
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
        $success['token'] =  $user->createToken('MyApp')->plainTextToken;
        $success['name'] =  $user->name;
   
        return $this->sendResponse($success, 'User register successfully.');
    }
   
    /**
     * Login api
     *
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')->plainTextToken; 
            $success['name'] =  $user->name;
   
            return $this->sendResponse($success, 'User login successfully.');
        } 
        else{ 
            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
        } 
    }
}
app/Http/Controllers/API/FoodController.php
<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\Food;
use Validator;
use App\Http\Resources\Food as FoodResource;

class FoodController extends BaseController
{
     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $foods = Food::all();
    
        return $this->sendResponse(FoodResource::collection($foods), 'Foods retrieved successfully.');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();
   
        $validator = Validator::make($input, [
            'name' => 'required',
            'detail' => 'required'
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $food = Food::create($input);
   
        return $this->sendResponse(new FoodResource($food), 'Food created successfully.');
    } 
   
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $food = Food::find($id);
  
        if (is_null($food)) {
            return $this->sendError('Food not found.');
        }
   
        return $this->sendResponse(new FoodResource($food), 'Food retrieved successfully.');
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Food $food)
    {
        $input = $request->all();
   
        $validator = Validator::make($input, [
            'name' => 'required',
            'detail' => 'required'
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $food->name = $input['name'];
        $food->detail = $input['detail'];
        $food->save();
   
        return $this->sendResponse(new FoodResource($food), 'Food updated successfully.');
    }
   
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Food $food)
    {
        $food->delete();
   
        return $this->sendResponse([], 'Food deleted successfully.');
    }
}
Step 7: Create Eloquent API Resources

Now In this step,This is a very important step of creating rest api in laravel 8. you can use eloquent api resources with api. it will helps you to make same response layout of your model object. we used in FoodController file. now we have to create it using following command.

php artisan make:resource Food

Now there created new file with new folder on following path:

app/Http/Resources/Food.php
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Food extends JsonResource
{
     /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'detail' => $this->detail,
            'created_at' => $this->created_at->format('d/m/Y'),
            'updated_at' => $this->updated_at->format('d/m/Y'),
        ];
    }
}

Now we are ready to to run full restful api and also passport api in laravel. so let's run our example so run bellow command for quick run:

php artisan serve

make sure in details api we will use following headers as listed bellow:

'headers' => [

    'Accept' => 'application/json',

    'Authorization' => 'Bearer '.$accessToken,
]
Now simply you can run above listed url like as bellow screen shot: 1) Register API: Verb:GET, URL:http://localhost:8000/api/register
Laravel 8 Sanctum API Authentication Tutorial
2) Login API: Verb:GET, URL:http://localhost:8000/api/login
Laravel 8 Sanctum API Authentication Tutorial
3) Food List API: Verb:GET, URL:http://localhost:8000/api/foods
Laravel 8 Sanctum API Authentication Tutorial
4) Food Create API: Verb:POST, URL:http://localhost:8000/api/foods
Laravel 8 Sanctum API Authentication Tutorial
5) Food Show API: Verb:GET, URL:http://localhost:8000/api/foods/{id}
Laravel 8 Sanctum API Authentication Tutorial
6) Food Update API: Verb:PUT, URL:http://localhost:8000/api/foods/{id}
Laravel 8 Sanctum API Authentication Tutorial
7) Food Delete API: Verb:DELETE, URL:http://localhost:8000/api/food/{id}
Laravel 8 Sanctum API Authentication Tutorial
It wiil help you....