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

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