Laravel Livewire Generate Slug Tutorial

Laravel Livewire Generate Slug Tutorial

Hey Dev,

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

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

Step 1 : Install Laravel App

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

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

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

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

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

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

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

composer require cviebrock/eloquent-sluggable

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

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

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

use Cviebrock\EloquentSluggable\Sluggable;

class Post extends Model
{
    use Sluggable;

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

Step 5 : Create Post Table

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

php artisan make:model Post -m
database/migrations/2021_06_05_044246_create_posts_table.php
<?php

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

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

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

namespace App\Models;

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

class Post extends Model
{
    use HasFactory,Sluggable;

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

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

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

php artisan make:livewire Posts

Now they created fies on both path:

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

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

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

namespace App\Http\Livewire;

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

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

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

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

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

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

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

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

resources/views/livewire/home.blade.php
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="{{ asset('js/app.js') }}" defer></script>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js" integrity="sha512-XKa9Hemdy1Ui3KSGgJdgMyYlUg1gM+QhL6cnlyTe2qzMCYm4nAZ1PsVerQzTTXzonUR+dmswHqgJPuwCq1MaAg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" integrity="sha512-P5MgMn1jBN01asBgU0z60Qk4QxiXo86+wlFahKrsQf37c9cro517WzVSPPV1tDKzhku2iJ2FVgL67wG03SGnNA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    @livewireStyles
</head>
<body class="bg-dark">
    <div class="container mt-5">
        <div class="row justify-content-center mt-5">
            <div class="col-md-8 mt-5">
                <div class="card">
                    <div class="card-header">
                        <h4>Laravel Livewire Slug Example</h4>
                    </div>
                    <div class="card-body">
                        @if (session()->has('message'))
                            <div class="alert alert-success">
                                {{ session('message') }}
                            </div>
                        @endif
                        @livewire('posts')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
</body>
</html>
resources/views/livewire/posts.blade.php
<div>
    <form wire:submit.prevent="store">
        <div class="form-group row">
            <label for="title" class="col-md-2 col-form-label text-md-right">Title</label>
            <div class="col-md-6">
                <input wire:model="title"
                       type="text"
                       class="form-control @error('title') is-invalid @enderror"
                       autofocus>

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

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

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

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

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

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/posts

It will help you..

Laravel Inertia JS Pagination Example

Laravel Inertia JS Pagination Example

Hi Guys,

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

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

Here, I will give you full example for inertia js pagination using Laravel as bellow.

Step 1 : Install Laravel 8

In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

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

In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3: Install Laravel Breeze

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

composer require laravel/breeze --dev

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

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

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

routes/web.php
<?php
  
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
  
use App\Http\Controllers\UserController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('/', function () {
    return Inertia::render('Welcome', [
        'canLogin' => Route::has('login'),
        'canRegister' => Route::has('register'),
        'laravelVersion' => Application::VERSION,
        'phpVersion' => PHP_VERSION,
    ]);
});
  
Route::get('/dashboard', function () {
    return Inertia::render('Dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');
 
Route::get('users', [UserController::class, 'index']);
  
require __DIR__.'/auth.php';
Step 5: Create Controller

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

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

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

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

now you can simple run bellow command:

npm run dev

Run laravel app with bellow command:

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

It will help you...

Laravel Validation Regex Pattern Tutorial

Laravel Validation Regex Pattern Tutorial

Hi Guys,

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

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

here the example of laravel validation allow only numbers let see below the solution solution
$request->validate([
	'project_name' => 'required|regex:/(^([a-zA-z]+)(\d+)?$)/u',
]);
Valid values for project name:
itwebtuts
itwebtuts
itwebtuts
Invalid values for project name:
123itwebtuts
!itwebtuts
itwebtuts 123
it webtuts
it webtuts123
Route : routes/web.php
<?php
use App\Http\Controllers\BlogController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('blogs',[BlogController::class,'index']);
Route::post('blogs',[BlogController::class,'store'])->name('blogs.store');
Controller : app/Http/Controllers/BlogController.php
<?php

namespace App\Http\Controllers;

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

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

Laravel 8 Sanctum API Authentication Tutorial

Laravel 8 Sanctum API Authentication Tutorial

Hi Dev,

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

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

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

Step 1 : Install Laravel 8

In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

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

In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 1: Install Laravel 8

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

composer require laravel/sanctum

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

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

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

php artisan migrate

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

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

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

In model we added HasApiTokens class of Sanctum,

In auth.php, we added api auth configuration.

app/Models/User.php
<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
  
class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
  
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
  
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}
Step 4: Add Food Table and Model

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

php artisan make:migration create_foods_table

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

<?php

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

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

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

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

php artisan migrate

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

app/Models/Food.php
<?php

namespace App\Models;

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

class Food extends Model
{
    use HasFactory;

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

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

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

namespace App\Http\Controllers\API;

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

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


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

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


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

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

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

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

namespace App\Http\Controllers\API;

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

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

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

php artisan make:resource Food

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

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

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

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

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

php artisan serve

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

'headers' => [

    'Accept' => 'application/json',

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

Laravel Create Custom Log File Example

Laravel Create Custom Log File Example

Hi Guys,

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

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

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

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

Laravel 8 Pluck Example Tutorial

Laravel 8 Pluck Example Tutorial

Hi Guys,

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

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

Example: 1

Here example single column for the returned Collection

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

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

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

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

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

JQuery Get and Set Image Src Tutorial

JQuery Get and Set Image Src Tutorial

Hi Guys,

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

Get Image Src

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

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

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

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

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

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

It Will help you....

Laravel 8 Pagination Tutorial Example

Laravel 8 Pagination Tutorial Example

Hi Guys,

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

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

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

Step 1: Add Route

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

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ProductController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('product', [ProductController::class, 'index']);
Step 2: Create Controller

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

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

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

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

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

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

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

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

Pagination with appends parameter

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

Pagination with appends request all parameters

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

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

It will help you..

Laravel Treeview Create Multi Level Dynamic Menu Tutorial

Laravel Treeview Create Multi Level Dynamic Menu Tutorial

Hii Dev,

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

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

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

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

Step 1 : Install Laravel 8 Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog
Database Configuration

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

1.Database Username

2.Database Password

3.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:

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

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

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

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

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

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your model file for create Menu table.

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

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

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

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

following path:/routes/web.php
<?php
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\MenuController;
    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */
    Route::get('menus',[MenuController::class,'index']);
    Route::get('menus-show',[MenuController::class,'show']);
    Route::post('menus',[MenuController::class,'store'])->name('menus.store');
Step 4: Create Controller

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

php artisan make:controller MenuController

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

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

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

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

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

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

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

1)menuTreeview.blade.php

2)manageChild.blade.php

3)dynamicMenu.blade.php

4)menusub.blade.php

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

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

here following include blade fille

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

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

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

here following include blade fille

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

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

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

This is require js file

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

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

php artisan serve

open bellow URL to create menu on your browser:

http://localhost:8000/menus

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

http://localhost:8000/menus-show

It will help you...

Laravel Arr where() function Example

Laravel Arr where() function Example

Hi Dev,

Today,I will learn you how to use laravel array where() function example. We will show example of array where function in laravel.The Arr::where method filters an array using the given Closure:

Here, I will give you full example for simply Arr where() method in laravel as bellow.

Example
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\FileController;
use Illuminate\Support\Arr;

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $array = [100, 'Laravel', 300, 'Php', 500];
        $filtered = Arr::where($array, function ($value, $key) {
                return is_string($value);
        });

        print_r($filtered);
        //[1 => 'Laravel', 3 => 'Php']

        $array2 = [100, '200', 300, '400', 500];

        $filtered2 = Arr::where($array2, function ($value, $key) {
            return is_string($value);
        });

        print_r($filtered2);
        // [1 => '200', 3 => '400']
    }
}
Output
"[1 => '200', 3 => '400']"
" [1 => 'Laravel', 3 => 'Php']"

It Will help you...

Laravel 8 Model Observers Example Tutorial

Laravel 8 Model Observers Example Tutorial

Hi Dev,

Nowdays,i will analyze you a way to use laravel 8 observers. this example will help you a way to use laravel 8 model observers. i would love to expose you what is observers in laravel 8. This tutorial will come up with simple instance of laravel eight model observers.

We can come up with very simple definition and use of laravel observers is, when you want to generate slug or auto generate precise identification or something like common sense add earlier than or after create document then observers will help you. i can come up with bellow events that provide via observers and easy instance bellow.

Here, i will give you complete instance for in reality model Observers the usage of Laravel eight as bellow.

Eloquent Hook

->Retrieved: after a record has been retrieved.

->Creating: before a record has been created.

->Created: after a record has been created.

->Updating: before a record is updated.

->Updated: after a record has been updated.

->Saving: before a record is saved (either created or updated).

->Saved: after a record has been saved (either created or updated).

->Deleting: before a record is deleted or soft-deleted.

->Deleted: after a record has been deleted or soft-deleted.

->Restoring: before a soft-deleted record is going to be restored.

->Restored: after a soft-deleted record has been restored.

Example:

Now In this blog,we will see simple example, i have one Food model and it has name, slug, price and unique_id column. so i need to create one record with name an price only. but when it's create i need to generate slug from name and auto generate unique_id.

app/Models/Food.php
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Food extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name', 'price', 'slug', 'unique_id'
    ];
}

Create observers class for Food. So, create bellow command:

php artisan make:observer FoodObserver --model=Food
app/Observers/FoodObserver.php
<?php
  
namespace App\Observers;
  
use App\Models\Food;
  
class FoodObserver
{
  
    /**
     * Handle the Food "created" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function creating(Food $food)
    {
        $food->slug = \Str::slug($food->name);
    }
  
    /**
     * Handle the Food "created" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function created(Food $food)
    {
        $food->unique_id = 'PR-'.$food->id;
        $food->save();
    }
  
    /**
     * Handle the Food "updated" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function updated(Food $food)
    {
          
    }
  
    /**
     * Handle the Food "deleted" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function deleted(Food $food)
    {
          
    }
  
    /**
     * Handle the Food "restored" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function restored(Food $food)
    {
          
    }
  
    /**
     * Handle the Food "force deleted" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function forceDeleted(Food $food)
    {
          
    }
}

Register Observers class on provider.

app/Providers/EventServiceProvider.php
<?php
  
namespace App\Providers;
  
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use App\Observers\FoodObserver;
use App\Models\Food;
  
class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];
  
    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        Food::observe(FoodObserver::class);
    }
}

Create Demo Route:

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

Create Controller Route:

app/Http/Controllers/FoodController.php
<?php
  
namespace App\Http\Controllers;
  
use App\Models\Food;
use Illuminate\Http\Request;
  
class FoodController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
  
        $food = Food::create([
            'name' => 'Milk',
            'price' => 30
        ]);
  
        dd($food);
    }
}

Now you can run project.

It will help you...

Laravel WhereHas Eloquent Example

Laravel WhereHas Eloquent Example

Hi Guys,

Today,I will learn you how to laravel wherehas eloquent. you will learn about laravel eloquent whereHas() with example. we show example of wherehas eloquent in laravel.you can easily use laravel wherehas eloquent.

Here I will give you example of laravel wherehas eloquent.

Example WhereHas Eloquent

Now this example, If you need even more power, you may use the whereHas methods to put "where" conditions on your has queries.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Country;

class BlogController extends Controller
{  

  /**
   * Write code on Method
   *
   * @return response()
   */
   public function index()
   {
       $country = Country::whereHas('blogs', function($q){
                      $q->where('name', '=', 'Good Info');
                   })->get();  
       dd($country->toArray());
   }
}
Output
array:1 [
  0 => array:5 [
    "id" => 1
    "name" => "test"
    "blogs_id" => 1
    "created_at" => null
    "updated_at" => null
  ]
]

It will help you..

Laravel 8 Download File Example

Laravel 8 Download File Example

Hi Dev,

In this blog,I'm able to examine you how to download report in laravel 8. we are able to display instance of reaction download with document in laravel 8.We now and again require to go back reaction with download document from controller technique like generate invoice and deliver to download or and so on.Laravel eight provide us response() with down load approach that way we are able to do it.

Here, First argument of down load() I ought to give route of down load document. we will rename of download record through passing second argument of download(). We can also set headers of file with the aid of passing third argument.

So, first i am going to create new route for our instance as like bellow:

routes/web.php
<?php
use App\Http\Controllers\DownloadFileController;

/*
|--------------------------------------------------------------------------
| 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('/file-download', [DownloadFileController::class, 'index'])->name('file.download.index');

Now,I have to add one method "downloadFile()" in my DownloadFileController. If you don't have DownloadFileController then you can use your own controller as like bellow:

App\Http\Controllers\DownloadFileController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DownloadFileController extends Controller
{
    public function index()
    {
    	$filePath = public_path("dummy.pdf");
    	$headers = ['Content-Type: application/pdf'];
    	$fileName = time().'.pdf';

    	return response()->download($filePath, $fileName, $headers);
    }
}

It will help you...

Laravel Validation timezone Example

Laravel Validation timezone Example

Hi Guys,

Today, I will learn you to create validation timezone in laravel.we will show example of laravel validation timezone.The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

Here, I will give you full example for simply timezone validation in laravel bellow.

solution
$request->validate([
  'time_zone' => 'timezone',
]);
Route : routes/web.php
Route::get('form/create','FormController@index');
Route::post('form/store','FormController@store')->name('form.store');
Controller : app/Http/Controllers/FormController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Blade;
use App\Models\User;
use App\Models\Post;

class FormController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('form');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $request->validate([
          'time_zone' => 'timezone'
        ]);
      dd('done');
    }
}
View : resources/views/form.php
<!DOCTYPE html>
<html>
<head>
  <title>From</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />
  <scrtimezonet src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></scrtimezonet>
  <scrtimezonet src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></scrtimezonet>
</head>
<body class="bg-dark">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header">
            <div class="row">
              <div class="col-md-9">
                 Laravel Validation timezone Example
              </div>
              <div class="col-md-3 text-right">
                <a href="{{ route('form') }}" class="btn btn-sm btn-outline-primary">Back</a>
              </div>
            </div>
          </div>
          <div class="card-body">
            @if (count($errors) > 0)
                  <div class="row">
                      <div class="col-md-12">
                          <div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                              @foreach($errors->all() as $error)
                              {{ $error }} <br>
                              @endforeach      
                          </div>
                      </div>
                  </div>
                @endif
              <form action="{{ route('from.store') }}" method="post">
                @csrf
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group">
                      <label>Your Timezone:</label>
                      <input name="time_zone" type="text" class="form-control">
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-12">
                    <button class="btn btn-block btn-success">Submit</button>
                  </div>
                </div>
              </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

It will help you...