SEO Most Important Meta Tags Tutorial

SEO Most Important Meta Tags Tutorial

Hi Dev,

In this blog,I will explain most important meta tags in seo. We will show SEO Most usefull Meta Tags.Link building is especially often touted as the “single most important thing to optimize”.Part of that strategy includes using HTML meta tags – a crucial component for SEO success.

Here, I will give you full example for important seo meta tags bellow.

1: Title Tag Title tag is your main and most important anchor.Title tag is typically appears as a clickable headline in the SERPs and also shows up on social networks and in browsers. Example
<title>SEO Most Important Meta Tags Tutorial</title>

This tag is placed in the <head> of your webpage and are meant to provide a clear and comprehensive idea of what the page is all about.The page’s title still is the first thing for a searcher to see in SERPs and decide if the page is likely to answer the search intent.

The simple experiment can also show that Google no longer needs your title tag to include an exact match keyword to know the topic the page covers.

Note:

->The titles up to 50-60 characters long (for them not to get truncated in the SERPs). Remember that long titles are shortened to about 600-700px on the SERP.

->Give each page a unique title that describes the page’s content concisely and accurately.

->Create use of your brand name in the title, even if it ends up not being shown on the SERPs, it’ll still make a difference for the search engine.

2: Meta Description Tag

The Meta description also resides in the of a webpage and is commonly (though definitely not always) displayed in a SERP snippet along with a title and page URL.

<meta name="description" content="NiceSnippets Blog provides you latest Code Tutorials on PHP, Laravel, Codeigniter, JQuery, Node js, React js, Vue js, PHP, and Javascript. Mobile technologies like Android, React Native, Ionic etc."/>

Description tag occupies the largest part of a SERP snippet and invites searchers to click on your site by promising a clear and comprehensive solution to their query.

This description tag is impacts the number of clicks you get, and may also improve CTR and decrease bounce rates if the pages’ content indeed fulfills the promises. That’s why the description must be as realistic as it is inviting and distinctly reflect the content.

Note:

->Cretae page a unique meta description that clearly reflects what value the page carries.

->Google’s snippets typically max out around 150-160 characters (including spaces).

->Description tag in use an eye-catchy call-to-action, a unique proposition you offer, or additional hints on what to expect ‘Purchase’,'Blog' constructions, etc.

3: Meta Keyword tag

The Meta keywords are types of meta tags in the HTML source code of a webpage. They describe the content of a website shortly and concisely, and are therefore important indicators of a website's content to search engines.

Meta keywords are generally written in lower case, and separated with a comma. Today, meta keywords are irrelevant for search engine optimization and don't have any ranking relevance.

<meta name="keywords" content="metatags, metakeywords" />
Note

->Always use a unique,and never stuff your keyword in this tag.

->Google’s snippets typically max out around 150-160 keyword.

4: Image Alt Attributes

The required alt attribute specifies an alternate text for an image, if the image cannot be displayed. The image alt attribute is added to an image tag to describe its contents.The alt attribute provides alternative information for an image if a user for some reason cannot view it (because of slow connection, an error in the src attribute, or if the user uses a screen reader).

<img src="img_car.jpg" alt="car image" width="500" height="600">

Google also says it outright: helping search engines understand what the images are about and how they go with the rest of the content may help them serve a page for suitable search queries.A thought-out image alt description, according to Mueller, is also vital if you want to rank in Google Images.

Search engines can’t read images, which are a crucial part of many websites. Alternative text (alt text) is a way around that issue.

Note:

->Always use a proper description, and never stuff your keyword in this tag

->Do your best to optimize the most prominent images (product images, infographics, or training images), images that are likely to be looked up in Google Images search.

->Use 50-55 characters (up to 16 words) in the alt text

->The alt text clear and descriptive enough, use your keywords reasonably, and make sure they fit naturally into the whole canvas of page’s content.

5: Open Graph Meta Tags and Twitter Cards

These tags make social media syncing easier.Open Graph was initially introduced by Facebook to let you control how a page would look when shared on social media.

Here is a sample of How Open Graph tags look like in standard HTML:

og:title

The og:title tag you put the title which you want to be displayed when your page is linked to.

<meta property="og:title" content="Title Of Page" />
og:description

your page’s description. Remember that Facebook will display only about 300 characters of description.

<meta property="og:description" content="Description Of Page Content" />
og:image

The og:image tag you can put the URL of an image you want to be shown when your page is linked to.

<meta property="og:image" content="Link to the image file" />
og:url

The og:image tag you can put the URL of an page.

<meta property="og:url" content="Permalink" />

Twitter cards work in a similar way to Open Graph, except for Twitter.Twitter will use these tags to enhance the display of your page when shared on their platform.

Here is a sample of How Twitter card look like in standard HTML.

twitter:title

The twitter:title tag you put the title which you want to be displayed when your page is linked to.

<meta name="twitter:title" content="Title Of Page">
twitter:description

your page’s description. Remember that twitter will display only about 160 characters of description.

<meta property="twitter:description" content="Description Of Page Content" />
twitter:image

The twitter:image tag you can put the URL of an image you want to be shown when your page is linked to.

<meta property="twitter:image" content="Link to the image file" />

Use the specific social media meta tags in order to boost how your links look to your following.it’s not a huge tweak, and it doesn’t influence your rankings on the search engines.however, by configuring how the links to your pages look, you can greatly boost your ctr and ux metrics.

Note:

->Make basic and relevant metadata using Open Graph protocol, and test the URLs to see how they will be displayed.

->Twitter cards and validate them once done.

6: Viewport Meta Tag

The final important meta tag is the responsive design meta tag, which is also called the viewport meta element.Viewport meta tag allows you to configure how a page would be scaled and displayed on any device.

<meta name="viewport" content="width=device-width, initial-scale=1"/>

Where “width=device-width” will make the page match the screen’s width in device-independent pixels, and “initial scale=1” will establish a 1:1 relationship between CSS pixels and device-independent pixels, taking screen orientation into account.Viewport meta tag has nothing to do with rankings directly but has a tone to do with the user experience.

It’s especially important considering the variety of devices that are being used nowadays and the noticeable shift to mobile browsing.As with many of the tags and tweaks we’ve discussed in this article, taking care of the viewport meta tag will be something your users appreciate.

7: Robots Meta Tag

The robots meta tag tells search engines to either index or non-index your web page. A page-level robots meta tag with content=“noindex” attribute instructs the search engines not to index any given page.

While these tags don’t correlate with rankings directly, in some cases they may have some impact on how your site looks in the eyes of search engines overall.

In some other cases, you may want certain pages to stay out of SERPs as they feature some kind of special deal that is supposed to be accessible by a direct link only (e.g., from a newsletter).you probably wouldn’t want such pages to be taken into account while evaluating the overall quality of your site. Here the following syntax for your robots meta tag.

Means not to index or not to follow this webpage.

<meta name=”robots” content=”noindex, nofollow”>

Means index and follow this webpage.

<meta name=”robots” content=”index, follow”> 
Note:

->Close pages that unreasonably waste crawl budget.

->Make sure carefully you don’t mistakenly restrict important pages from indexing.

->Close unnecessary/unfinished pages with thin content that have little value and no intent to appear in the SERPs.

It will 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 8 View Render Example

Laravel 8 View Render Example

Hi Dev,

In this blog,I will share you how to view render in laravel 8.you can easy and simply view render in laravel 8.

So, we utilize get html view layout from ajax request. At that you have to first render view file and then you require to store view in varibale and then we can return that varibale. In bellow example i render view with pass data you can visually perceive how i did:

Here, i Will giev you a simple example how to view render with ajax you can check the code and copy it.

Step 1 : Create Route

In this step,you can create route file in laravel.

routes/web.php
<?php
use App\Http\Controllers\RenderController;
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('view', [RenderController::class, 'index']);
Route::post('view/render', [RenderController::class, 'renderView'])->name('view.render');
Step 2 : Create Controller

In this second step we will now we should create new controller as RenderController. So run bellow command and create new controller.

php artisan make:controller RenderController

After you create successfully RenderController above command you will find new file in this path app/Http/Controllers/RenderController.php.

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

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class RenderController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
    	return view('render.index');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function renderView(Request $request)
    {
    	$renderview = view('render.renderView')->render();
    	return response()->json([
    		'success' => true,
    		'html'=>$renderview
    	]);
    }
}

Step 3: Create Blade File Path : resources/views/render/renderView.blade.php
<!DOCTYPE html>
<html>
<head>
	<title>Laravel 8 View Render Example</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
	<div class="container">
		<div class="row">
			<div class="col-md-12">
				<h3>Laravel 8 View Render Example</h3>
				<p>MyWebTuts specifically for sharing programming issue and examples. We’ll be sharing some chunks of codes of PHP, Laravel Framework, CSS3, HTML5, MYSQL, Bootstrap, CodeIgniter Framework, JQuery, Javascript, Server, Ionic Framework etc. In our site i am sure you will find something good solution and find example of topics of PHP, Laravel etc.</p>
			</div>
		</div>
	</div>
</body>
</html>
Path : resources/views/render/index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Laravel 8 View Render Example</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
	<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
	<style>
		body{
			background:#f7fcff !important;
		}
		.wrapper{
			margin-top: 250px;
		}
		.wrapper h3{
			margin-bottom:25px !important ;
			text-align: center;
		}
		.wrapper p{
			text-align: center;
		}
	</style>
</head>
<body>
	<div class="container">
		<div class="row">
			<div class="col-md-12 wrapper">
				<div class="viewRender">
					
				</div>
			</div>
		</div>
	</div>
	<script type="text/javascript">
		$(document).ready(function(){
			$_token = "{{ csrf_token() }}";
			$.ajax({
			 	headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') },
				type:"POST",
		        url: "{{ route('view.render') }}",
		        cache:"false",
    	        data: {'_token': $_token },
    	        datatype:"html",
    	        beforeSend: function() {
	            	//something before send
	        	},
	        	success:function (data) {
	        		console.log(data);
	        		$('.viewRender').html(data.html);
	        	}
			});
		});
	</script>
</body>
</html>

It will help you...

Laravel Livewire Generate Slug Tutorial

Laravel Livewire Generate Slug Tutorial

Hey Dev,

Today, I would really like to percentage with you how to generate slug in laravel livewire .i will display you a complete instance for generate slug example with laravel livewire. we will talk approximately a way to create Livewire slug in laravel.

Livewire is a full-stack framework for Laravel that makes building dynamic interfaces easy, with out leaving the comfort of Laravel.Livewire is based entirely on AJAX requests to do all its server communicaton. right here i can provide complete example for laravel livewire generate slug example,So we could follow the bellow step.

Step 1 : Install Laravel App

In First step, We need to get fresh laravel version application using bellow command. So Let's open terminal and run bellow command.

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

After successfully install laravel app thenafter configure databse setup. We will open ".env" file and change the database name, username and password in the env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password
Step 3 : Install Livewire

In this step, You will simply install livewire to our laravel application using bellow command:

composer require livewire/livewire
Step 4 : Install "cviebrock/eloquent-sluggable" Package

In this step, You will simply install "cviebrock/eloquent-sluggable" for generate slug to our laravel application using bellow command:

composer require cviebrock/eloquent-sluggable

The package will automatically register its service provider.publish the configuration file if you want to change any defaults using bellow command:

php artisan vendor:publish --provider="Cviebrock\EloquentSluggable\ServiceProvider"

Your models should use the Sluggable trait, which has an abstract method sluggable() that you need to define. This is where any model-specific configuration is set (see Configuration below for details):

use Cviebrock\EloquentSluggable\Sluggable;

class Post extends Model
{
    use Sluggable;

    /**
     * Return the sluggable configuration array for this model.
     *
     * @return array
     */
    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'title'
            ]
        ];
    }
}

Step 5 : Create Post Table

In this step, We have to create migration for blogs table using bellow artisan command. So let's open terminal and run bello command :

php artisan make:model Post -m
database/migrations/2021_06_05_044246_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->string('slug');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
App/Models/Post.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;

class Post extends Model
{
    use HasFactory,Sluggable;

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

    /**
     * Return the sluggable configuration array for this model.
     *
     * @return array
     */
    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'title'
            ]
        ];
    }
}
Step 6 : Create Component

Now, You can create livewire component using bellow command, So Let's run bellow command to create Posts form component:

php artisan make:livewire Posts

Now they created fies on both path:

app/Http/Livewire/Posts.php
resources/views/livewire/posts.blade.php

Now first file we will update as bellow for Posts.php file.

app/Http/Livewire/Posts.php
<?php

namespace App\Http\Livewire;

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

class Posts extends Component
{
    public $title;
    public $slug;

    public function render()
    {
        $posts = Post::latest()->take(5)->get();
        return view('livewire.posts', compact('posts'));
    }

    public function updatedTitle()
    {
        $this->slug = SlugService::createSlug(Post::class, 'slug', $this->title);
    }

    public function store()
    {
        Post::create([
            'title' => $this->title,
            'slug'  => $this->slug
        ]);
        $this->title = '';
        $this->slug = '';
    }
}
Step 7 : Add Route

In this step, we need to add route for Show posts and create post in laravel application. so open your "routes/web.php" file and add following route.

routes/web.php
Route::view('posts','livewire.home');
Step 8 : Create View

Here, we will create blade file for call modal route. in this file we will use @livewireStyles, @livewireScripts and @livewire('posts'). so let's add it.

resources/views/livewire/home.blade.php
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="{{ asset('js/app.js') }}" defer></script>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <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" />
    @livewireStyles
</head>
<body class="bg-dark">
    <div class="container mt-5">
        <div class="row justify-content-center mt-5">
            <div class="col-md-8 mt-5">
                <div class="card">
                    <div class="card-header">
                        <h4>Laravel Livewire Slug Example</h4>
                    </div>
                    <div class="card-body">
                        @if (session()->has('message'))
                            <div class="alert alert-success">
                                {{ session('message') }}
                            </div>
                        @endif
                        @livewire('posts')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
</body>
</html>
resources/views/livewire/posts.blade.php
<div>
    <form wire:submit.prevent="store">
        <div class="form-group row">
            <label for="title" class="col-md-2 col-form-label text-md-right">Title</label>
            <div class="col-md-6">
                <input wire:model="title"
                       type="text"
                       class="form-control @error('title') is-invalid @enderror"
                       autofocus>

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

        <div class="form-group row">
            <label for="slug" class="col-md-2 col-form-label text-md-right">Slug</label>
            <div class="col-md-6">
                <input wire:model="slug"
                       type="text"
                       class="form-control @error('slug') is-invalid @enderror">

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

        <div class="form-group row mb-0">
            <div class="col-md-8 offset-md-4">
                <button type="submit" class="btn btn-primary">
                    Add Post
                </button>
            </div>
        </div>
    </form>
    <table class="table table-bordered mt-2">
        <thead>
            <tr>
                <th>Name</th>
                <th>Slug</th>
            </tr>
        </thead>
        <tbody>
            @if($posts->count())
                @foreach ($posts as $post)
                    <tr>
                        <td>{{ $post->title }}</td>
                        <td>{{ $post->slug }}</td>
                    </tr>
                @endforeach
            @endif
        </tbody>
    </table>
</div>

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/posts

It will 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 Validation Regex Pattern Tutorial

Laravel Validation Regex Pattern Tutorial

Hi Guys,

In this blog,I will learn how to validation regex pattern in laravel. you can easy to use validation number in laravel we are show the 6 regex pattern validation. we will field under validation allow only regex pattern string in laravel

In this example,you can simply apply to validation to regex pattern Validation in laravel. The field under validation must have a regex pattern value.

here the example of laravel validation allow only numbers let see below the solution solution
$request->validate([
	'project_name' => 'required|regex:/(^([a-zA-z]+)(\d+)?$)/u',
]);
Valid values for project name:
itwebtuts
itwebtuts
itwebtuts
Invalid values for project name:
123itwebtuts
!itwebtuts
itwebtuts 123
it webtuts
it webtuts123
Route : routes/web.php
<?php
use App\Http\Controllers\BlogController;
/*
|--------------------------------------------------------------------------
| 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('blogs',[BlogController::class,'index']);
Route::post('blogs',[BlogController::class,'store'])->name('blogs.store');
Controller : app/Http/Controllers/BlogController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Notifications\Notification;

class BlogController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('index');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      $request->validate([
        "project_name" => "required|regex pattern"
      ]);
      return redirect()->back();
    }
}
View : resources/views/index.php
<!DOCTYPE html>
<html>
<head>
  <title>From</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header">
            <div class="row">
              <div class="col-md-9">
                 Laravel Validation Regex Pattern Example
              </div>
              <div class="col-md-3 text-right">
                <a href="{{ route('form') }}" class="btn btn-sm btn-outline-primary">Back</a>
              </div>
            </div>
          </div>
          <div class="card-body">
                @if (count($errors) > 0)
                      <div class="row">
                          <div class="col-md-12">
                              <div class="alert alert-danger alert-dismissible">
                                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                                  @foreach($errors->all() as $error)
                                  {{ $error }} <br>
                                  @endforeach      
                              </div>
                          </div>
                      </div>
                    @endif
              <form action="{{ route('from.store') }}" method="post">
                @csrf
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group">
                      <label>Project Name:</label>
                      <input name="project_name" type="text" class="form-control">
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-12">
                    <button class="btn btn-block btn-success">Submit</button>
                  </div>
                </div>
              </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>   
It will 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....

Laravel Create Custom Log File Example

Laravel Create Custom Log File Example

Hi Guys,

Today,I will learn you how to create custom log file in laravel? This article will give you simple example of laravel custom log file example. it's simple example of create custom log file in laravel. Follow bellow tutorial step of how to make custom log file laravel.

Laravel by default provide storage/logs/laravel.log file location where it will display log file. but sometime you may require to create log file with specific task. for example, if you are working with payment task and you need all logs separately log file for payment, so you can easily find out solution.

Here, i will give you very simple example, so let's see how to add custom channel with new log file location.

config/logging.php
...
'channels' => [
        ...
        'itwebtuts' => [
            'driver' => 'single',
            'path' => storage_path('logs/itwebtuts.log'),
            'level' => 'info',
        ],
....
Route Code:
Route::get('create-custom-log', function () {
    \Log::channel('itwebtuts')->info('This is testing for itwebtuts.com!');
    dd('done');
});
now you can check your own. storage/logs/itwebtuts.log
[2021-04-13 11:46:41] local.INFO: This is testing for itwebtuts.com!  
It will help you....

Laravel 8 Pluck Example Tutorial

Laravel 8 Pluck Example Tutorial

Hi Guys,

Today,i will learn how you can use pluck method in laravel 8. we are show simple example of pluck query builder example in laravel 8. you can table to get array in values using laravel pluck method.

It can get value column and key using pluck method.pluck method to returned collection single column or specify a custom key column following example.

Example: 1

Here example single column for the returned Collection

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
   
   $ids = \DB::table('posts')->pluck('id');

   dd($ids);
}
Output
array:[
    0 => 1
    1 => 2
    2 => 3
   ]
Example: 2

>Here example specify a custom key column for the returned Collection

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
   
   $users  = User::pluck('name','id');

   dd($users);
}
Output
array:4 [
    1 => "abc"
    2 => "xyz"
    3 => "mno"
  ]
It will help you...

JQuery Get and Set Image Src Tutorial

JQuery Get and Set Image Src Tutorial

Hi Guys,

Today, I will learn you how to get and set image src in jquery. We will show easy example of jquery get and set image src.The attr() method to get and change the image source in jQuery.

Get Image Src

In this example,I will Use the below script to get image src.

$(document).ready(function() {
  $('.btn').click(function(){
    $imgsrc = $('img').attr('src');
    alert($imgsrc);
   });
});
Set the Image Src

In this example,I will Use the below script to set image src.

$(document).ready(function() {
  $('.btn').click(function(){
    $("img").attr("src",'test.png');
  });
});
Full Example

Now,The following example will change the second image to the first image.

<html>
<head>
  <title> How to get and set image src attribute example</title>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   
  <script>
    $(document).ready(function() {
      $('.btn').click(function(){
        $imgsrc = $('#first').attr('src');
        $("#second").attr("src",$imgsrc);
      });
    });
  </script>
  <style>
    .card{
      margin: 30px;
    }
  </style>
</head>
<body>
  <div class="card">
    <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNSCowfKvdA_XwYJ4PViv9gQ-q50eeykM2E9FIdmSlIakgoW5QckWzOFc-WSBIZkBGkRXcefsoRVoPfP2UDM7qxUkoVc1IWSxhlZ0ZHx40BgJMO9eDkq1vQ18JWIhLW0C5W9owKiMdShmT/s0/Laravel+Custom+ENV+Variables+Tut.png" width="100" id="first" alt="Blog Image"">
  </div>
  <div class="card">
    <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpipA6pqFifEWR4qswk86MZvHOBRC9JKkJhtSTDDoQYfe-mDETt1DGzsLy1X_i9bwNBdHnM812ftqImUIZqvjtBponL-G36pDZ4wVWzhjfKphtGgVf5NaL5J5q_2mEO9MX_2XpPe5nu04Q/s0/laravel-email-vali.png" width="100" id="second" alt="Blog Image">
  </div>
  <button type="type" class="btn">Get & Set image src</button>
</body>
</html>

It Will help you....

Laravel 8 Pagination Tutorial Example

Laravel 8 Pagination Tutorial Example

Hi Guys,

Today, I will learn you how to create pagination with laravel 8.If you want to full example of laravel 8 pagination example blade. if you have question about laravel 8 pagination with user table then i will give simple and easy example with solution for you. i explained simply step by step laravel 8 pagination tutorial. let’s talk about pagination in laravel 8.

We know pagination is a primary requisite of each and every project. so if you are a beginner with laravel than you must know how to utilize pagination in laravel 8 and what is other function that can utilize with laravel 8 pagination.

Now, In this example i will explain you from scratch how to working with laravel pagination. so let's follow bellow step by step tutorial for creating simple example of pagination with laravel 8.

Step 1: Add Route

First all of we put one route in one for list users with pagination. So simply add both routes in your route file.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ProductController;
  
/*
|--------------------------------------------------------------------------
| 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('product', [ProductController::class, 'index']);
Step 2: Create Controller

Same things as above for route, here we will add one new method for route. index() will return users with pagination data, so let's add bellow:

app/Http/Controllers/ProductController.php
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Product;
  
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Product::paginate(5);
        return view('product.index',compact('data'));
    }
}
Step 3: Create Blade File

After create ProductController you need to create index blade file and put bellow code with links() so it will generate pagination automatically. So let's put it.

resources/views/index.blade.php
    
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
    <style type="text/css">
        .form-inline{
            display: inline;
        }
    </style>
</head>
<body class="bg-dark">
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h3>Laravel 8 Pagination Example Tutorial</h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-hover">
                            <thead class="bg-secondary text-white">
                                <tr>
                                    <th>#</th>
                                    <th>Product Name</th>
                                    <th>Product Price</th>
                                    <th>Product Details</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @if(!empty($products) && $products->count())
                                    @foreach($products as $key => $product)
                                        <tr>
                                            <td>{{ ++$key }}</td>
                                            <td>{{ $product->name }}</td>
                                            <td>{{ $product->price }}</td>
                                            <td>{{ $product->details }}</td>
                                            <td>
                                                  <button class="btn btn-danger btn-icon">
                                                    <i class="far fa-trash-alt text-white" data-feather="delete"></i>
                                                  </button>
                                            </td>
                                        </tr>
                                    @endforeach
                                    @else
                                        <tr>
                                            <td colspan="10">There are no data.</td>
                                        </tr>
                                    @endif
                            </tbody>
                        </table>
                        {!! $products->links() !!}
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Now you can run and check this example. it is a very simple and basic example.

If you are using bootstrap then you have to add useBootstrap() on service provider as like bellow:

app\Providers\AppServiceProvider.php
<?php
  
namespace App\Providers;
  
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;
  
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
    
    }
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Paginator::useBootstrap();
    }
}

If you need advance used of pagination then you can see bellow how to use.

Pagination with appends parameter

{!! $data->appends(['sort' => 'votes'])->links() !!}

Pagination with appends request all parameters

{!! $data->appends(Request::all())->links() !!}

You can also see in advance details from here: Laravel 8 Pagination.

It will help you..

Laravel Treeview Create Multi Level Dynamic Menu Tutorial

Laravel Treeview Create Multi Level Dynamic Menu Tutorial

Hii Dev,

In this blog, I will explain how can create dynamic multi level menu in laravel we will create example of multi level dynamic menu in laravel you can easy to make many level dynamic menu in laravel.

In this tutorial i simple create "menus" table and manage end level of parents and child menu with nested tree view structure in Laravel application. I use jquery for make tree view layout and child relationship with menu model for hierarchical data. I also add form for create new menu in tree view.I also create dynamic drop down menu using bootstrap nav.

If you are new in laravel then also you can do it simple and also simply customize it because this tutorial from scratch. You can simple following bellow step, you will multi level dynamic menu in your application as bellow preview and also you can check demo.

here following example step of multi level dynamic menu in laravel treeview

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

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

In this step we have to create migration and model for menus table using Laravel 8 php artisan command, so first fire bellow command:

php artisan make:model Menu -m
After this command you have to put bellow code in your migration file for create menus table. following path:/database/migrations/2020_01_10_102325_create_menus_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

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

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

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

following path:/app/Models/Menu.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Menu extends Model
{
    protected $fillable = ['title','parent_id'];

    public function childs() {
        return $this->hasMany('App\Menu','parent_id','id') ;
    }
}
Step 3: Create Route

In this is step we need to create route for tree menu show layout file , create menu for post method route and show dynamic menus.

following path:/routes/web.php
<?php
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\MenuController;
    /*
    |--------------------------------------------------------------------------
    | 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('menus',[MenuController::class,'index']);
    Route::get('menus-show',[MenuController::class,'show']);
    Route::post('menus',[MenuController::class,'store'])->name('menus.store');
Step 4: Create Controller

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

php artisan make:controller MenuController

now this step, this controller will manage menu layout and create menu with validation with post request,bellow content in controller file. i added three method in this controller as listed bellow:

1)index() 2)store() 3)show() following path:/app/Http/Controllers/MenuController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Menu;

class MenuController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(){
   
       $menus = Menu::where('parent_id', '=', 0)->get();
       $allMenus = Menu::pluck('title','id')->all();
       return view('menu.menuTreeview',compact('menus','allMenus'));
   
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
       $request->validate([
           'title' => 'required',
        ]);

       $input = $request->all();
        $input['parent_id'] = empty($input['parent_id']) ? 0 : $input['parent_id'];
        Menu::create($input);
         return back()->with('success', 'Menu added successfully.');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function show()
    {
        $menus = Menu::where('parent_id', '=', 0)->get();
        return view('menu.dynamicMenu',compact('menus'));
    }
}
Step 5: Create View

In this step, we have to create menu folder in total four blade file as listed bellow:

1)menuTreeview.blade.php

2)manageChild.blade.php

3)dynamicMenu.blade.php

4)menusub.blade.php

This both blade file will help to render menu tree structure, so let's create both file view file and put bellow code.

following path:/resources/views/menu/menuTreeview.blade.php
<!DOCTYPE html>
<html>
<head>
   <title>Multi Level Dynamic Menu In Laravel Treeview</title>
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" />
   <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css">
   <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
   <link href="/css/treeview.css" rel="stylesheet">
</head>
<body class="bg-dark">
<div class="container">
   <div class="row">
      <div class="col-md-10 offset-md-1 mt-4">
         <div class="card">
            <div class="card-header">
               <h5>Multi Level Dynamic Menu In Laravel Treeview</h5>
            </div>
            <div class="card-body">
               <div class="row">
                  <div class="col-md-6">
                     <h5 class="mb-4 text-center bg-success text-white ">Add New Menu</h5>
                     <form accept="{{ route('menus.store')}}" method="post">
                        @csrf
                         @if(count($errors) > 0)
                                  <div class="alert alert-danger  alert-dismissible">
                                      <button type="button" class="close" data-dismiss="alert">×</button>
                                      @foreach($errors->all() as $error)
                                              {{ $error }}<br>
                                      @endforeach
                                  </div>
                              @endif
                          @if ($message = Session::get('success'))
                           <div class="alert alert-success  alert-dismissible">
                               <button type="button" class="close" data-dismiss="alert">×</button>   
                                   <strong>{{ $message }}</strong>
                           </div>
                        @endif
                        <div class="row">
                           <div class="col-md-12">
                              <div class="form-group">
                                 <label>Title</label>
                                 <input type="text" name="title" class="form-control">   
                              </div>
                           </div>
                        </div>
                        <div class="row">
                           <div class="col-md-12">
                              <div class="form-group">
                                 <label>Parent</label>
                                 <select class="form-control" name="parent_id">
                                    <option selected disabled>Select Parent Menu</option>
                                    @foreach($allMenus as $key => $value)
                                       <option value="{{ $key }}">{{ $value}}</option>
                                    @endforeach
                                 </select>
                              </div>
                           </div>
                        </div>
                        <div class="row">
                           <div class="col-md-12">
                              <button class="btn btn-success">Save</button>
                           </div>
                        </div>
                     </form>
                  </div>
                  <div class="col-md-6">
                     <h5 class="text-center mb-4 bg-info text-white">Menu List</h5>
                      <ul id="tree1">
                         @foreach($menus as $menu)
                            <li>
                                {{ $menu->title }}
                                @if(count($menu->childs))
                                    @include('menu.manageChild',['childs' => $menu->childs])
                                @endif
                            </li>
                         @endforeach
                        </ul>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>
<script src="/js/treeview.js"></script>
</body>
</html>

here following include blade fille

following path:/resources/views/menu/manageChild.blade.php
  <ul>
  @foreach($childs as $child)
     <li>
         {{ $child->title }}
     @if(count($child->childs))
              @include('manageChild',['childs' => $child->childs])
          @endif
     </li>
  @endforeach
  </ul>

After This both blade file will help to render dynamic drop down menu view file, so let's create both file view file and put bellow code.

following path:/resources/views/menu/dynamicMenu.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="https://bootstrapthemes.co/demo/resource/bootstrap-4-multi-dropdown-hover-navbar/css/bootstrap-4-hover-navbar.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
<nav class="navbar navbar-expand-md navbar-light bg-light btco-hover-menu">
    <a class="navbar-brand" href="#">Nicesnippets.com</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavDropdown">
        <ul class="navbar-nav">
            @foreach($menus as $menu)
            <li class="nav-item dropdown">
                <a class="nav-link {{ count($menu->childs) ? 'dropdown-toggle' :'' }}" href="https://bootstrapthemes.co" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                   {{ $menu->title }}
                </a>
                <ul class="dropdown-menu " aria-labelledby="navbarDropdownMenuLink">
                  @if(count($menu->childs))
                    @include('menu.menusub',['childs' => $menu->childs])
                  @endif
                </ul>
            </li>
            @endforeach
        </ul>
    </div>
</nav>
<div style="position: absolute; left:2%; top:55%;">
  <h2 class="bg-white p-2 shadow-lg rounded">Multi Level Dynamic Menu In Laravel Treeview</h2>
</div>
</body>
</html>

here following include blade fille

following path:/resources/views/menu/menusub.blade.php
 @foreach($childs as $child)
 <li>
      <a class="dropdown-item {{ count($child->childs) ? 'dropdown-toggle' :'' }}" href="#" style="border:1px solid #ccc;">{{ $child->title }}</a>
       @if(count($child->childs))
          <ul class="dropdown-menu">
              <li>
                 <a class="dropdown-item" href="#" style="position: absolute;">
                       @include('menu.menusub',['childs' => $child->childs])
                    </a>
                </li>
            </ul>
        @endif
   </li>
 @endforeach
Preview:Menu treeview hierarchical structure Step 6: Add CSS and JS File

In last step, we have to add one css file and one js file for treeview design. I simply use bootsnipp css and js code, so let's create css and js file as following path:

following path:public/css/treeview.css
.tree, .tree ul {
    margin:0;
    padding:0;
    list-style:none
}
.tree ul {
    margin-left:1em;
    position:relative
}
.tree ul ul {
    margin-left:.5em
}
.tree ul:before {
    content:"";
    display:block;
    width:0;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    border-left:1px solid
}
.tree li {
    margin:0;
    padding:0 1em;
    line-height:2em;
    color:#369;
    font-weight:700;
    position:relative
}
.tree ul li:before {
    content:"";
    display:block;
    width:10px;
    height:0;
    border-top:1px solid;
    margin-top:-1px;
    position:absolute;
    top:1em;
    left:0
}
.tree ul li:last-child:before {
    background:#fff;
    height:auto;
    top:1em;
    bottom:0
}
.indicator {
    margin-right:5px;
}
.tree li a {
    text-decoration: none;
    color:#369;
}
.tree li button, .tree li button:active, .tree li button:focus {
    text-decoration: none;
    color:#369;
    border:none;
    background:transparent;
    margin:0px 0px 0px 0px;
    padding:0px 0px 0px 0px;
    outline: 0;
}

This is require js file

following path:public/js/treeview.js
$.fn.extend({
    treed: function (o) {
      
        var openedClass = 'glyphicon-minus-sign';
        var closedClass = 'glyphicon-plus-sign';
      
        if (typeof o != 'undefined'){
          if (typeof o.openedClass != 'undefined'){
            openedClass = o.openedClass;
          }
          if (typeof o.closedClass != 'undefined'){
            closedClass = o.closedClass;
          }
        }
      
        /* initialize each of the top levels */
        var tree = $(this);
        tree.addClass("tree");
        tree.find('li').has("ul").each(function () {
            var branch = $(this);
            branch.prepend("");
            branch.addClass('branch');
            branch.on('click', function (e) {
                if (this == e.target) {
                    var icon = $(this).children('i:first');
                    icon.toggleClass(openedClass + " " + closedClass);
                    $(this).children().children().toggle();
                }
            })
            branch.children().children().toggle();
        });
        /* fire event from the dynamically added icon */
        tree.find('.branch .indicator').each(function(){
            $(this).on('click', function () {
                $(this).closest('li').click();
            });
        });
        /* fire event to open branch if the li contains an anchor instead of text */
        tree.find('.branch>a').each(function () {
            $(this).on('click', function (e) {
                $(this).closest('li').click();
                e.preventDefault();
            });
        });
        /* fire event to open branch if the li contains a button instead of text */
        tree.find('.branch>button').each(function () {
            $(this).on('click', function (e) {
                $(this).closest('li').click();
                e.preventDefault();
            });
        });
    }
});
/* Initialization of treeviews */
$('#tree1').treed();

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

php artisan serve

open bellow URL to create menu on your browser:

http://localhost:8000/menus

Now you can open bellow URL to dropdown nav menu on your browser:

http://localhost:8000/menus-show

It will help you...