Laravel 8 Jetstream Livewire CRUD App Tutorial

Laravel 8 Jetstream Livewire CRUD App Tutorial

Hello Guys,

In this blog, I will learn you livewire crud with jetstream in laravel 8 application. We will learn laravel 8 jetstream livewire crud app example. I would like to share with you how perform crud opeartion livewire with jetstream in laravel 8 application.

This blog will give you easy and simple example of laravel 8 jetstream livewire crud app example. In this example i will show you step by step laravel 8 livewire crud app with modal tailwind css.

Laravel 8 jetstream designed by Tailwind CSS and they provide auth using livewire and Inertia. i will show you how to create module with livewire on default jetstream auth in laravel 8.

Here i will give you full example for laravel 8 jetstream livewire crud app example. So let's follow bellow step by step:

Step 1 : Install Laravel 8 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 : Create Jetstream Auth with Livewire:

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

composer require laravel/jetstream

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

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
Step 3 : Create Migration and Model

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:migration create_blogs_table
database/migrations/2020_09_26_044246_create_blogs_table.php
<?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('title');
            $table->text('body');
            $table->timestamps();
        });
    }

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

now we will create Blog model by using following command:

php artisan make:model Blog
App/Models/Blog.php
<?php

namespace App\Models;

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

class Blog extends Model
{
    use HasFactory;

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

Here this step, We have to create blog livewire component using bellow command. So let's open terminal and run bello command :

php artisan make:livewire blogs

Now they created fies on both path:

app/Http/Livewire/Blogs.php
resources/views/livewire/blogs.blade.php
Step 5 : Update Component File

Here We will write render(), create(), openModal(), closeModal(), resetInputFields(), store(), edit() and delete() method for our crud app.

So, let, update following file.

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

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Blog;

class Blogs extends Component
{
   public $blogs, $title, $body, $blog_id;
    public $isOpen = 0;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function render()
    {
        $this->blogs = Blog::all();
        return view('livewire.blogs');
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function create()
    {
        $this->resetInputFields();
        $this->openModal();
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function openModal()
    {
        $this->isOpen = true;
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function closeModal()
    {
        $this->isOpen = false;
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    private function resetInputFields(){
        $this->title = '';
        $this->body = '';
        $this->blog_id = '';
    }
     
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function store()
    {
        $this->validate([
            'title' => 'required',
            'body' => 'required',
        ]);
   
        Blog::updateOrCreate(['id' => $this->blog_id], [
            'title' => $this->title,
            'body' => $this->body
        ]);
  
        session()->flash('message', 
            $this->blog_id ? 'Blog Updated Successfully.' : 'Blog Created Successfully.');
  
        $this->closeModal();
        $this->resetInputFields();
    }
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function edit($id)
    {
        $blog = Blog::findOrFail($id);
        $this->blog_id = $id;
        $this->title = $blog->title;
        $this->body = $blog->body;
    
        $this->openModal();
    }
     
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function delete($id)
    {
        Blog::find($id)->delete();
        session()->flash('message', 'Blog Deleted Successfully.');
    }
}
Step 6 : Update Blade Files

Here, we will update following list of files for our listing page, create page.

So, let, update following file.

resources/views/livewire/blogs.blade.php
<x-slot name="header">
    <h2 class="font-semibold text-xl text-gray-800 leading-tight">
        Manage blogs (Laravel 8 Jetstream Livewire CRUD App Example)
    </h2>
</x-slot>
<div class="py-12">
    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg px-4 py-4">
            @if (session()->has('message'))
                <div class="bg-teal-100 border-t-4 border-teal-500 rounded-b text-teal-900 px-4 py-3 shadow-md my-3" role="alert">
                  <div class="flex">
                    <div>
                      <p class="text-sm">{{ session('message') }}</p>
                    </div>
                  </div>
                </div>
            @endif
            <button wire:click="create()" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded my-3">Create New Blog</button>
            @if($isOpen)
                @include('livewire.create')
            @endif
            <table class="table-fixed w-full">
                <thead>
                    <tr class="bg-gray-100">
                        <th class="px-4 py-2 w-20">No.</th>
                        <th class="px-4 py-2">Title</th>
                        <th class="px-4 py-2">Body</th>
                        <th class="px-4 py-2">Action</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($blogs as $blog)
                    <tr>
                        <td class="border px-4 py-2">{{ $blog->id }}</td>
                        <td class="border px-4 py-2">{{ $blog->title }}</td>
                        <td class="border px-4 py-2">{{ $blog->body }}</td>
                        <td class="border px-4 py-2">
                        <button wire:click="edit({{ $blog->id }})" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Edit</button>
                            <button wire:click="delete({{ $blog->id }})" class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">Delete</button>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>
resources/views/livewire/create.blade.php
<div class="fixed z-10 inset-0 overflow-y-auto ease-out duration-400">
    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <!-- This element is to trick the browser into centering the modal contents. -->
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen"></span>?
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full" role="dialog" aria-modal="true" aria-labelledby="modal-headline">
            <form>
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <div class="">
                        <div class="mb-4">
                            <label for="exampleFormControlInput1" class="block text-gray-700 text-sm font-bold mb-2">Title:</label>
                            <input type="text" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="exampleFormControlInput1" placeholder="Enter Title" wire:model="title">
                            @error('title') <span class="text-red-500">{{ $message }}</span>@enderror
                        </div>
                        <div class="mb-4">
                            <label for="exampleFormControlInput2" class="block text-gray-700 text-sm font-bold mb-2">Body:</label>
                            <textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="exampleFormControlInput2" wire:model="body" placeholder="Enter Body"></textarea>
                            @error('body') <span class="text-red-500">{{ $message }}</span>@enderror
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <span class="flex w-full rounded-md shadow-sm sm:ml-3 sm:w-auto">
                        <button wire:click.prevent="store()" type="button" class="inline-flex justify-center w-full rounded-md border border-transparent px-4 py-2 bg-green-600 text-base leading-6 font-medium text-white shadow-sm hover:bg-green-500 focus:outline-none focus:border-green-700 focus:shadow-outline-green transition ease-in-out duration-150 sm:text-sm sm:leading-5">
                        Save
                        </button>
                    </span>
                    <span class="mt-3 flex w-full rounded-md shadow-sm sm:mt-0 sm:w-auto">
                        <button wire:click="closeModal()" type="button" class="inline-flex justify-center w-full rounded-md border border-gray-300 px-4 py-2 bg-white text-base leading-6 font-medium text-gray-700 shadow-sm hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue transition ease-in-out duration-150 sm:text-sm sm:leading-5">
                            Cancel
                        </button>
                    </span>
                </div>
            </form>
        </div>
    </div>
</div>
Step 7 : Add Route

In third step, we will create routes for jetstream crud with livewire .

routes/web.php
<?php
use App\Http\Livewire\Blogs;

Route::get('blog', Blogs::class);

Now we are ready to run our laravel 8 jetstream livewire crud app example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/blog

It will help you...

Laravel Jetstream Login with Phone Number and Password Example

Laravel Jetstream Login with Phone Number and Password Example

Hii Dev,

This article will provide example of laravel jetstream login with phone number. This article goes in detailed on login with mobile number and password in laravel jetstream. In this article, we will implement a laravel jetstream login with mobile number. i would like to share with you laravel jetstream login with phone number example.

I will give you step by step adding login with phone number in laravel jetstream. you can easily integrate with laravel 6, laravel 7 and laravel 8 version.

after installing laravel jetstream successfully. you need to do following changes on that files:

app/Providers/FortifyServiceProvider.php
<?php
  
namespace App\Providers;
  
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use App\Actions\Fortify\UpdateUserPassword;
use App\Actions\Fortify\UpdateUserProfileInformation;
use Illuminate\Support\ServiceProvider;
use Laravel\Fortify\Fortify;
use Laravel\Fortify\Http\Requests\LoginRequest;
use App\Models\User;
use Hash;
  
class FortifyServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
          
    }
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Fortify::createUsersUsing(CreateNewUser::class);
        Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
        Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
        Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
  
        Fortify::authenticateUsing(function (LoginRequest $request) {
            $user = User::where('phone_number', $request->phone_number)->first();
  
            if (
                $user &&
                Hash::check($request->password, $user->password)
            ) {
                return $user;
            }
        });
    }
}
config/fortify.php
'username' => 'phone_number',
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="{{ __('Phone Number') }}" />
                <x-jet-input class="block mt-1 w-full" type="text" name="phone_number" :value="old('phone_number')" 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>
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

It will help you....

Laravel Call Controller Method From Another Method Example

Laravel Call Controller Method From Another Method Example

Hi Dev,

Today,I will learn you how to call controller method from another method in laravel. I will show example of laravel call controller method from another method.you can easliy call controller method from another method in laravel.

I will describe step by step laravel call controller method from another method example.

Step 1: Create Route

In this setp,I will create route for a call controller method from another method in laravel.

<?php
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('/home', [UserController::class,'index'])->name('home');
Step 2: Create Controller

In this setp, I will create two controller using terminal/cmd. I will create UserController and AdminController.

php artisan make:UserController
and
php artisan make:AdminController
Step 3:User Controller

In this setp, i will writer code of call controller method from another method.

<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
    	$id = 1;

        $result = (new AdminController)->index($id);

        return view('home',compact('result'));
    }
}

Step 4:Admin Controller

In this setp, i will create method in admin controller for code of call controller method from another method.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Admin;

class AdminController extends Controller
{
    public function index($id)
    {
        dd('This is AdminController Index Method Id='.$id);
    }
}

OutPut
"This is AdminController Index Method And Id=1"
It will help you....

Laravel Livewire Select2 Multiple Tutorial

Laravel Livewire Select2 Multiple Tutorial

Hi Dev,

Today, I would like to share with you how to inetegrate select2 livewire in laravel application.I will show you a complete example for select2 multiple example with laravel livewire.

Livewire is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel.Livewire relies solely on AJAX requests to do all its server communicaton.

Here I will give full example for select2 in laravel livewire,So Lets 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 : Create Post Table

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

php artisan make:model Product -m
database/migrations/2021_06_05_044246_create_products_table.php
<?php

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

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

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

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;
    protected $fillable = ['name','category'];
}
Step 5 : Create Component

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

php artisan make:livewire Select2

Now they created fies on both path:

app/Http/Livewire/Select2.php
resources/views/livewire/select2.blade.php

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

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

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Product;

class Select2 extends Component
{
    public $productList = [
        'Fruit',
        'Vegetable',
        'Chocolate',
        'Egg',
        'Fish',
        'Chemical',
        'Dairy Product',
    ];

    public $name,$category = [];

    public function render()
    {
        return view('livewire.select2');
    }

    public function store()
    {
        $input = [
            'name' => $this->name,
            'category' => json_encode($this->category),
        ];
        Product::create($input);
        $this->name = '';
        $this->category = '';
        $this->emit('productStore');
    }
}
Step 6 : Add Route

Now, we need to add route for create select2 dropdown and create product in laravel application. so open your "routes/web.php" file and add following route.

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

Here, we will create blade file for call 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>Laravel Livewire Select2 Multiple Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <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" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    @livewireStyles
</head>
<body>
    <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 bg-info text-white">
                        <h4>Laravel Livewire Select2 Multiple Example </h4>
                    </div>
                    <div class="card-body">
                        @if (session()->has('message'))
                            <div class="alert alert-success">
                                {{ session('message') }}
                            </div>
                        @endif
                        @livewire('select2')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
    @stack('scripts')
</body>
</html>
resources/views/livewire/select2.blade.php
<div>
    <form wire:submit.prevent="store">
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" wire:model="name" class="form-control">
                </div>
            </div>
            <div class="col-md-12">
                <div class="form-group">
                    <label>Category</label>
                    <div wire:ignore>
                        <select id="category-dropdown" class="form-control" multiple wire:model="category">
                            @foreach($productList as $product)
                                <option value="{{$product}}">{{ $product }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-md-12 text-center">
                <button type="submit" class="btn btn-success">Save</button>
            </div>
        </div>
    </form>
</div>
@push('scripts')
    <script>
        $(document).ready(function () {
            $('#category-dropdown').select2();
            $('#category-dropdown').on('change', function (e) {
                let data = $(this).val();
                 @this.set('category', data);
            });
            window.livewire.on('productStore', () => {
                $('#category-dropdown').select2();
            });
        });  
    </script>
@endpush
Now we are ready to run our example so run bellow command for quick run:
php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/select2

It will help you..

Laravel Custom Setter Tutorial Example

Laravel Custom Setter Tutorial Example

Hey Dev,

Today, I will learn you how to laravel custom setter tutorial in your laravel project.The laravel custom setter tutorial is so easy to use.so you can just follow my step by step and learn laravel custom setter tutorial.

So let's start to the example and follow to the my all step.

Solution
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
public function setPasswordAttribute($password)
{
    $this->attributes['password'] = bcrypt($password);
}
Step 1: Create a Employee model

Now Let's started our first step to create a Employee.php models and use this code.

Path : App/Models/Employee.php
<?php

namespace App\Models;

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

class Employee extends Model
{
    use HasFactory;

    public $table = "employee";

    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'username',
        'password',
    ];

    /**
     * Write code on Method
     *
     * @return response()
     */
     protected $hidden = [
        'password',
    ];

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }
}

Step 2: Create Route

create a route in web.php file and use this code.

Path : routes/web.php
<?php

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

/*
|--------------------------------------------------------------------------
| 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('emp-create', [EmployeeController::class, 'create'])->name('emp.create');
Route::post('emp-store', [EmployeeController::class, 'store'])->name('emp.store');

Step 3: Create a EmployeeController

Next you can require to the EmployeeController so create a EmployeeController in just following command through.

php artisan make:controller EmployeeController
Path : app/Http/Controllers/EmployeeController.php
<?php

namespace App\Http\Controllers;

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

class EmployeeController extends Controller
{

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('employee');
    }
 
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function store(Request $request)
    {

        $data = [
            'username' => $request->username,
            'password' => $request->password,
        ];

        $emp = Employee::create($data);
        dd($emp);
    }

}
Step 4: Create a employee Blade File

Next you can require to the employee.blade.php so create a employee.blade.php in your resources/views directory folder.

Path : resources/views/employee.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Custom Setters Tutorial</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body> 
   
<div class="container mt-5">
    <h1 class="text-center">Laravel Custom Setters Tutorial</h1>

    {!! Form::open(array('route' => 'emp.store','method'=>'POST')) !!}
        <div class="col-md-12">
            <div class="row mt-0">
                <div class="col-md-6">
                    <div class="form-group pl-3 pr-3">
                        <label>Username</label>
                        {{ Form::text('username', null ,['class'=>'form-control', 'placeholder'=>'User Name'] ) }}
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group pl-3 pr-3">
                        <label>Password</label>
                        {{ Form::password('password',['class'=>'form-control', 'placeholder'=>'Enter Password'] ) }}
                    </div>
                </div>
                <div class="col-md-12 text-center mt-2 mb-3">
                    <button type="submit" class="btn btn-success">Submit</button>
                </div>
            </div>
        </div>
    {!! Form::close() !!}
</div>
   
</body>
</html>

Ok, now you have to create some dummy records on employee table.

So, finally we are done with our code we can get below output.

php artisan serve
Browser url run : http://localhost:8000/emp-create
output:
App\Models\Employee {#293 ▼
  +table: "employee"
  #fillable: array:2 [▶]
  #hidden: array:1 [▶]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: true
  #attributes: array:5 [▶]
  #original: array:5 [▼
    "username" => "andy"
    "password" => "$2y$10$6PEjNQHqiVvm.3hPl64AKOlaWP.40rqL/Hobu/wy2cT.2dCvv/WQ6"
    "updated_at" => "2021-05-24 06:34:03"
    "created_at" => "2021-05-24 06:34:03"
    "id" => 8
  ]
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [▶]
}

It Will Help You...

Laravel Custom Getter Example

Laravel Custom Getter Example

Hey Dev,

Today, i will learn you how to laravel custom getter tutorial in your laravel project.The laravel custom getter tutorial is so easy to use.so you can just follow my step by step and learn laravel custom getter tutorial.

In this article we have three subject now we are getting three subject total marks how this possible now we can use laravel Getter function let's implement and here we go jump to full example follow my bellow step

So let's start to the example and follow to the my all step.

Solution:
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
public function getStudentTotalMarkAttribute()
{
     return $this->seo_marks + $this->laravel_marks + $this->science_marks;
}
Step 1: Create a Student Controller

Next, you can require to the Student Controller so create a Student Controller in just following command through.

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

namespace App\Http\Controllers;

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

class StudentController extends Controller
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    public function index(Request $request)
    {
        $student = Student::find(1);
        dd($student->studentTotalMark);
    }
}
Step 2: Create a Student model

Last step to create a Student.php models and use this code.

Path : App/Models/Student.php
<?php

namespace App\Models;

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

class Student extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = [
        'name',
        'seo_marks',
        'laravel_marks',
        'science_marks',
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    // Total Marks
    public function getStudentTotalMarkAttribute()
    {
        return $this->seo_marks + $this->laravel_marks + $this->science_marks;
    }
}

Step 3: Create Route

Last step to create a route in web.php file and use this code.

Path : routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;
/*
|--------------------------------------------------------------------------
| 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('student-profile', [StudentController::class, 'index'])->name('student');

Ok, now you have to create some dummy records on users table.

So, finally we are done with our code we can get below output.

php artisan serve

Now you can open bellow URL on your browser:

Browser url run : http://localhost:8000/student-profile
It will help you...

Laravel 8 Multiple Delete Records With CheckBox Example

Laravel 8 Multiple Delete Records With CheckBox Example

Hi Guys,

In this blog, I will learn how to implement delete multiple checkbox value in laravel 8 and other version so you are just following into the my steps in step by step and learn to the laravel 8 multiple checkbox to delete value.

So, let's start to the example and follow to the my all step.

Step 1: Create laravel 8 project

First step to create a fresh laravel 8 project in using bellow command.

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

This step to configure your database details in .env file.So let's create username, password etc. So let's add.

Path : .env
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: Create a students table

We require students table for the store in your value and students table field to require in name and email field.so create a product table in just following command.

php artisan make:migration create_students_table
Path : database/migrations/2021_06_09_062032_create_students_table.php
<?php

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

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

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

Then next to run your migration in following command.

php artisan migrate
Step 4: create a Student model

Next we can need to the Student model so create a Student model in just following command through.

php artisan make:model Student
Path : App\Models\Product.php
<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $fillable = ['name', 'email'];
}
Step 5: create Controller

Next, in this step we need to the StudentController so create a StudentController in just following command through.

php artisan make:Controller StudentController
app/Http/Controllers/StudentController.php
<?php

namespace App\Http\Controllers;

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

class StudentController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $studentsData = Student::get();
        return view('student',compact('studentsData'));
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function destory(Request $request,$id)
    {
        $input = $request->all();
        $data = Student::find($id);
        $data->delete($id);
        return response()->json(['success'=>"Product Deleted successfully.", 'tr'=>'tr_'.$id]);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function deleteAll(Request $request)
    {   
        $ids = $request->ids;
        Student::whereIn('id',explode(',',$ids))->delete(); 
        return response()->json(['success'=>"Products Deleted successfully."]);
    }
}

Step 6: Create Routes Path : routes/web.php
<?php
use App\Http\Controllers\StudentController;
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('/', [StudentController::class, 'index']);
Route::delete('students/{id}', [StudentController::class, 'destory']);
Route::delete('studentsDeleteAll', [StudentController::class, 'deleteAll']);
Step 7: Add Blade File Path : resources/views/student.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Laravel 8 - Multiple delete records with checkbox example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-confirmation/1.0.5/bootstrap-confirmation.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style type="text/css">
        body{
            background: #fcf3f2;
        }
        table{
            background: #f2f2f2;
        }
    </style>
</head>
<body>
    <div class="container wrapper">
        <div class="row">
            <div class="col-md-10 offset-1">
                <div class="card">
                    <div class="card-header">
                        <h4>Laravel 8 - Multiple delete records with checkbox example</h4>
                        <button style="margin-bottom: 15px;" class="btn btn-warning delete_all" data-url="{{ url('studentsDeleteAll') }}">Delete All Selected</button>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-hover">
                            <tr>
                                <th width="50px"><input type="checkbox" id="master"></th>
                                <th width="80px">No.</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th width="100px">Action</th>
                            </tr>
                            @if($studentsData->count())
                                @foreach($studentsData as $key => $studentData)
                                <tr id="tr_{{ $studentData->id }}">
                                    <td><input type="checkbox" class="sub_chk" data-id="{{$studentData->id}}"></td>
                                    <td>{{ ++$key }}</td>
                                    <td>{{ $studentData->name }}</td>
                                    <td>{{ $studentData->email }}</td>
                                    <td>
                                        <a href="{{ url('students',$studentData->id) }}" class="btn btn-danger btn-sm"
                                            data-tr="tr_{{$studentData->id}}"
                                            data-toggle="confirmation"
                                            data-btn-ok-label="Delete" data-btn-ok-icon="fa fa-remove"
                                            data-btn-ok-class="btn btn-sm btn-danger"
                                            data-btn-cancel-label="Cancel"
                                            data-btn-cancel-icon="fa fa-chevron-circle-left"
                                            data-btn-cancel-class="btn btn-sm btn-default"
                                            data-title="Are you sure you want to delete ?"
                                            data-placement="left" data-singleton="true">
                                            {{-- <i class="fas fa-trash"></i> --}}
                                            Delete
                                        </a>
                                    </td>
                                </tr>
                                @endforeach
                            @endif
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

<script type="text/javascript">
    $(document).ready(function(){
        $('#master').on('click',function (e) {
            if ($(this).is(':checked',true)) {
                $('.sub_chk').prop('checked',true)
            }else {
                $('.sub_chk').prop('checked',false)
            }
        });

        $('.delete_all').on('click',function (e) {
            var allVals = [];
            $('.sub_chk:checked').each(function () {
                allVals.push($(this).attr('data-id'));
            });

            if (allVals.length <= 0) {
                alert("Please select row.");
            }else {
                var check = confirm("Are you sure you want to delete this row?");
                if (check == true) {
                    var join_selected_values = allVals.join(",");

                    $.ajax({
                        url: $(this).data('url'),
                        type: 'DELETE',
                        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                        data:'ids='+join_selected_values,
                        success:function (data) {
                            console.log(data);
                            if (data['success']) {
                                $(".sub_chk:checked").each(function () {
                                    $(this).parents("tr").remove();
                                });
                                alert(data['success']);
                            } else if (data['success']){
                                alert(data['error']);
                            } else{
                                alert('Whoops Something went wrong!!');
                            }
                        },
                        error: function (data) {
                            alert(data.responseText);
                        }
                    });

                    $.each(allVals, function( index, value ){
                        $('table tr').filter("[data-row-id='" + value + "']").remove();
                    });
                }
            }
        });

        $('[data-toggle=confirmation]').confirmation({
            rootSelector: '[data-toggle=confirmation]',
            onConfirm: function (event, element) {
                element.trigger('confirm');
            }
        });

        $(document).on('confirm', function (e) {
            var ele = e.target;
            e.preventDefault();

            $.ajax({
                url: ele.href,
                type: 'DELETE',
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                success: function (data) {
                    if (data['success']) {
                        $("#" + data['tr']).slideUp("slow");
                        alert(data['success']);
                    } else if (data['error']) {
                        alert(data['error']);
                    } else {
                        alert('Whoops Something went wrong!!');
                    }
                },
                error: function (data) {
                    alert(data.responseText);
                }
            });

            return false;
        });
    });
</script>
</html>

So, finally we are done with our code we can get below output.

Run your project in following command:

php artisan serve
Browser url run : http://localhost:8000

I Hope It Will Help You..

Laravel Livewire Login Register Example

Laravel Livewire Login Register Example

Hii Dev,

Today, I will learn you how to create a login and dynamic user registration form using laravel livewire package. We will show laravel livewire create login and register page. In this article, I will show laravel livewire custom auth and regsiter tutorial i am going to show you create user login and register page in laravel livewire.

We have to create login and register page using livewire in laravel. I will show you create sign in and sign up page in laravel livewire.

Livewire is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel.Livewire relies solely on AJAX requests to do all its server communicaton.

Here I will give full example for login and register users livewire in laravel,So Lets 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 : Create Component

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

php artisan make:livewire LoginRegister

Now they created fies on both path:

app/Http/Livewire/LoginRegister.php
resources/views/livewire/login-register.blade.php

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

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

namespace App\Http\Livewire;

use Livewire\Component;
use Hash;
use App\User;

class LoginRegister extends Component
{
    public $users, $email, $password, $name;
    public $registerForm = false;

    public function render()
    {
        return view('livewire.login-register');
    }

    private function resetInputFields(){
        $this->name = '';
        $this->email = '';
        $this->password = '';
    }

    public function login()
    {
        $validatedDate = $this->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);
        
        if(\Auth::attempt(array('email' => $this->email, 'password' => $this->password))){
                session()->flash('message', "You are Login successful.");
        }else{
            session()->flash('error', 'email and password are wrong.');
        }
    }

    public function register()
    {
        $this->registerForm = !$this->registerForm;
    }

    public function registerStore()
    {
        $validatedDate = $this->validate([
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $this->password = Hash::make($this->password); 

        User::create(['name' => $this->name, 'email' => $this->email,'password' => $this->password]);

        session()->flash('message', 'Your register successfully Go to the login page.');

        $this->resetInputFields();

    }
}
Step 5 : Add Route

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

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

Here, we will create blade file for show login form and register form. in this file we will use @livewireStyles, @livewireScripts and @livewire('login-register'). so let's add it.

resources/views/livewire/login-register.blade.php
<div>
    <div class="row">
        <div class="col-md-12">
            @if (session()->has('message'))
                <div class="alert alert-success">
                    {{ session('message') }}
                </div>
            @endif
            @if (session()->has('error'))
                <div class="alert alert-danger">
                    {{ session('error') }}
                </div>
            @endif
        </div>
    </div>
    @if($registerForm)
        <form>
            <div class="row">
                <div class="col-md-12">
                    <div class="form-group">
                        <label>Name :</label>
                        <input type="text" wire:model="name" class="form-control">
                        @error('name') <span class="text-danger error">{{ $message }}</span>@enderror
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="form-group">
                        <label>Email :</label>
                        <input type="text" wire:model="email" class="form-control">
                        @error('email') <span class="text-danger error">{{ $message }}</span>@enderror
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="form-group">
                        <label>Password :</label>
                        <input type="password" wire:model="password" class="form-control">
                        @error('password') <span class="text-danger error">{{ $message }}</span>@enderror
                    </div>
                </div>
                <div class="col-md-12 text-center">
                    <button class="btn text-white btn-success" wire:click.prevent="registerStore">Register</button>
                </div>
                <div class="col-md-12">
                    <a class="text-primary" wire:click.prevent="register"><strong>Login</strong></a>
                </div>
            </div>
        </form>
    @else
        <form>
            <div class="row">
                <div class="col-md-12">
                    <div class="form-group">
                        <label>Email :</label>
                        <input type="text" wire:model="email" class="form-control">
                        @error('email') <span class="text-danger error">{{ $message }}</span>@enderror
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="form-group">
                        <label>Password :</label>
                        <input type="password" wire:model="password" class="form-control">
                        @error('password') <span class="text-danger error">{{ $message }}</span>@enderror
                    </div>
                </div>
                <div class="col-md-12 text-center">
                    <button class="btn text-white btn-success" wire:click.prevent="login">Login</button>
                </div>
                <div class="col-md-12">
                    Don't have account? <a class="btn btn-primary text-white" wire:click.prevent="register"><strong>Register Here</strong></a>
                </div>
            </div>
        </form>
    @endif
</div>
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">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    @livewireStyles
</head>
<body>
    <div class="container">
        <div class="row mt-5 justify-content-center">
            <div class="mt-5 col-md-8">
                <div class="card">
                    <div class="card-header bg-danger text-white"><h5 style="font-size: 23px;">Laravel Livewire - Login Register Example - NiceSnippets.com</h5></div>

                    <div class="card-body">
                        @livewire('login-register')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
</script>
</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/login

It will help you..

Laravel Livewire Multiple Image Upload Example

Laravel Livewire Multiple Image Upload Example

Hi Guys,

In this example, I would like to share you how to upload multiple image using livewire in laravel application. We will show multiple image upload in laravel livewire.

First, add the WithFileUploads trait to your component. Now you can use wire:model on file inputs as if they were any other input type and Livewire will take care of the rest.

Livewire makes uploading and storing files extremely easy.Livewire handles multiple file uploads automatically by detecting the multiple attribute on the <input> tag.

Here, I will give you full example for livewire multiple image upload in laravel. So Let's see the bellow example and follow 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 : Create image table and model

In this step, You have to create images table in your database. Run bellow command to create migration and modal So lets open terminal and run bellow command:

php artisan make:modal Image -m

After run above command, you will see a migration file in following path database/migrations and you have to simply put following code in migration file to create images table.

<?php

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

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

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

Run migration file and run following command:

php artisan migrate

After create 'images' table thenafter changes in Image modal copy bellow code and put in the Image.php file.

app/Image.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    protected $fillable = ['image'];
}
Step 4 : Install Livewire

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

composer require livewire/livewire
Step 5 : Create Component

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

php artisan make:livewire image-upload

Now they created fies on both path:

app/Http/Livewire/ImageUpload.php
resources/views/livewire/image-upload.blade.php

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

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

namespace App\Http\Livewire;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Image;

class ImageUpload extends Component
{
    use WithFileUploads;

    public $images = [];

    public function render()
    {
        return view('livewire.image-upload');
    }

    public function store()
    {
        $this->validate([
            'images.*' => 'image|max:1024', // 1MB Max
        ]);

        foreach ($this->images as $key => $image) {
            $this->images[$key] = $image->store('images','public');
        }

        $this->images = json_encode($this->images);

        Image::create(['image' => $this->images]);

        session()->flash('message', 'Image successfully Uploaded.');

        return redirect()->to('/mutliplt-image-upload');
    }
}
Step 6 : Add Route

Now, we need to add route for image form in laravel application. so open your "routes/web.php" file and add following route.

routes/web.php
Route::view('multiple-image-upload','livewire.home');
Step 7 : Create View

Here, we will create blade file for call crud opertaion route. in this file we will use @livewireStyles, @livewireScripts and @livewire('image-upload'). so let's add it.

resources/views/livewire/image-upload.blade.php
<div>
    <form>
        <div class=" add-input">
            <div class="row">
                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" class="form-control" wire:model="images" multiple>
                        @error('image.*') <span class="text-danger error">{{ $message }}</span>@enderror
                    </div>
                </div>
                <div class="col-md-12 text-center">
                    <button class="btn text-white btn-success" wire:click.prevent="store">Save</button>
                </div>
            </div>
        </div>
    </form>
</div>
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">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    @livewireStyles
</head>
<body>
    <div class="container">
        <div class="row mt-5 justify-content-center">
            <div class="mt-5 col-md-8">
                <div class="card">
                    <div class="card-header bg-primary text-white"><h3>Laravel Livewire Multiple Image Upload </h3></div>

                    <div class="card-body">
                        @if (session()->has('message'))
                            <div class="alert alert-success">
                                {{ session('message') }}
                            </div>
                        @endif

                        @livewire('image-upload')
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    @livewireScripts
</script>
</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/multiple-image-upload

It will help you...

Laravel Livewire Load More Tutorial

Laravel Livewire Load More Tutorial

Hello Dev,

Today, I will learn you how to load more data with scroll using livewire laravel application. We will show page scrolling with loading data in laravel livewire.In this artical, I will learn you load more data in laravel livewire. You can scroll page then load more data in livewire at that time use bellow example.

Livewire is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel.Livewire relies solely on AJAX requests to do all its server communicaton.

Here I will give full example for load more data livewire in laravel,So Lets 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 : Create Component

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

php artisan make:livewire users

Now they created fies on both path:

app/Http/Livewire/Users.php
resources/views/livewire/users.blade.php

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

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

namespace App\Http\Livewire;

use Livewire\Component;
use App\User;

class Users extends Component
{
    public $perPage = 8;
    protected $listeners = [
        'load-more' => 'loadMore'
    ];

    public function loadMore()
    {
        $this->perPage = $this->perPage + 5;
    }

    public function render()
    {
        $users = User::latest()->paginate($this->perPage);
        $this->emit('userStore');
        return view('livewire.users-list',['users' => $users]);
    }
}
Step 5 : Add Route

Now, we need to add route for list users in laravel application. so open your "routes/web.php" file and add following route.

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

Here, we will create blade file for show users list. in this file we will use @livewireStyles, @livewireScripts and @livewire('users'). so let's add it.

resources/views/livewire/users.blade.php
<div>
    <div class="table-responsive">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>No.</th>
                    <th>Name</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody>
                @foreach($users as $user)
                    <tr>
                        <td>{{ $user->id }}</td>
                        <td>{{ $user->name }}</td>
                        <td>{{ $user->email }}</td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</div>
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">
    @livewireStyles
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h2>Laravel Livewire Load More with Scroll</h2>
                    </div>
                    <div class="card-body">
                        @if (session()->has('message'))
                            <div class="alert alert-success">
                                {{ session('message') }}
                            </div>
                        @endif
                        @livewire('users')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
    <script type="text/javascript">
        window.onscroll = function(ev) {
            if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
                window.livewire.emit('load-more');
            }
        };
   </script>
</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/users

It will help you..

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