What is Chunk and Cursor?
Chunk: It will “paginate” your query, this way you use less memory.
* Uses less memory
* It takes longer
public function getData() {
Contact::chunk(1000, function ($contacts) {
foreach ($contacts as $contact) {
//rest of your code...
}
});
}
Cursor: You will use PHP Generators to search your query items one by one.
* It takes less time
* Uses more memory
public function getData() {
foreach (Contact::cursor() as $contact) {
//rest of your code...
}
}
Monday, 11 January 2021
What is Chunk and Cursor?
How to enable QueryLog?
use DB;
DB::connection()->enableQueryLog();
$data_array = DB::table('vendor')->where('vendor_id', '=', $uid)->get();
$x = DB::getQuerylog();
dd($x);
Sunday, 27 December 2020
419 Session Expired
How to remove 419 Session Expired error.
Step 1. In .env file SESSION_DRIVER=file. Replace file with database.
Example: SESSION_DRIVER=database.
Step 2. In the config/session.php
'driver' => env('SESSION_DRIVER', 'file'), Replace file with database
Example: 'driver' => env('SESSION_DRIVER', 'database'),
Step 3. Create a database name session.
php artisan session:table
php artisan migrate.
Friday, 25 December 2020
How to create shortcode in laravel
1. Create a middleware name PostShortCodeMiddleware
2. Add this middleware in the kernal file.
3. Create a shortcode.php and shorcodeurl.php in view folder.
4. Place the shortcode in any view file. I have placed it in home.blade.php
{user_list} {user_email}
<?php
namespace App\Http\Middleware;
use Closure;
use App\Post;
use DB;
use Illuminate\Http\Response;
class PostShortCodeMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);
if(!method_exists($response, 'content')):
return $response;
endif;
if(method_exists($response, 'content')){
$posts = DB::table('users')->select()->get();
$postslug = DB::table('users')->select('email')->get();
$content = str_replace(array('{user_list}', '{user_email}'), array(view('posts.shortcode',['posts' => $posts]), view('posts.shortcodeurl',['posts' => $postslug])), $response->content());
$response->setContent($content);
return $response;
}
}
}
Add in the Middleware
protected $middleware = [
.......
\App\Http\Middleware\PostShortCodeMiddleware::class,
......
];
shortcode.php
<table class="table table-bordered data-table">
<thead>
<tr>
<th width="50px">ID</th>
<th>Name</th>
<th>Email</th>
<th>Created</th>
<th>Updated</th>
</tr>
</thead>
<tbody>
<?php foreach ($posts as $post) {?>
<tr>
<td><?php echo $post->id; ?></td>
<td><?php echo $post->name; ?></td>
<td><?php echo $post->email; ?></td>
<td><?php echo $post->created_at; ?></td>
<td><?php echo $post->updated_at; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
shortcodeurl.php
<table class="table table-bordered data-table">
<thead>
<tr>
<th>User Email</th>
</tr>
</thead>
<tbody>
<?php foreach ($posts as $post) {?>
<tr>
<td><?php echo $post->email; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Friday, 18 December 2020
Important points to remember
Use stack for including css and js file..
<head>
<!-- Head Contents -->
@stack('css')
@stack('js')
</head>
In your template file
@push('css')
<link rel="stylesheet" href="/build/assets/css/laravel.css">
@endpush
@push('css')
<style> .....</style>
@endpush
@push('js')
<script src="/example.js"></script>
@endpush
******************** **************************************************
Option for isset
{{ isset($data) ? $data : "Not available" }}
{{ $data or "Not available" }}
***********************************************************************
To include a Blade view from within another view. All variables that are available to the parent view will be made available to the included view:
<div>
@include('shared.errors')
<form>
<!-- Form Contents -->
</form>
</div>
and may also pass an array of extra data to the included view:
@include('view.name', ['some' => 'data'])
*************************************************************************
In env file you can make production / local / staging
if (App::environment('local', 'staging')) {
// The environment is either local OR staging...
}
'debug' => env('APP_DEBUG', false),
*************************************************************************
To reduce the length of password in registration. Open the RegisterController and set the new
length.
'password' => ['required', 'string', 'min:4', 'confirmed'],
*************************************************************************
How To Bypass CSRF Token For A Route In Laravel?
Path:- /app/Http/Middleware/VerifyCsrfToken.php
Add Below Code In The Class:-
protected $except = [
'api/*', //For All Route starting with api.
'your_url_here/', //For Specific url.
];
*************************************************************************
Stopping On First Validation Failure
Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:
$request->validate([
'title' => 'bail|required|unique:posts|max:255',
'body' => 'required',
]);
*************************************************************************
If you do not want the validator to consider null values as invalid. For example:
$request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
'publish_at' => 'nullable|date',
]);
*************************************************************************
Reverse routing
From the controller and action name, convert back to the url.
In the web.php
Route::get('/mypage', 'HomeController@test');
you can change any name in route. You don't have to change in the blade file. The function
remains the same.
<a href="{{action('HomeController@test')}}"> Test Page</a>
HomeController
Class HomeController extends Controller {
function test() {
return 'Hi, This is test page';
}
}
*************************************************************************
Query Scope
I want 'active' Users from User table. Currently we are using where queries like this.
$activeUsers = User::where('status', 1)->get();
But we need same thing in any other module also. So we need write again and again this where queries. Now, we will use Scope Query. Create a scopeName function in model. Below is the user model.
public function scopeActive($query,$value)
{
return $query->where('status', $value);
}
In different module or controller
Use App\user;
In function you can use like this.
$data_array = User::active(0)->get();
*************************************************************************
Life cycle of Request

Tuesday, 8 December 2020
Factory and Seeder
Below is default factory. Factories ->UserFactory..
<?php
use App\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;
$factory->define(User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
});
Below is default Databaseseeders ->UserFactory..
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
factory(App\User::class, 100)->create();
}
}
Run
php artisan db:seed
Sunday, 6 December 2020
How to send email in Laravel 7 - 8
Step 1. Create mail
php artisan make:mail Contact Mail
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ContactMail extends Mailable
{
use Queueable, SerializesModels;
public $details;
public function __construct($details)
{
$this->details = $details;
}
public function build()
{
return $this->view('email');
}
}
Step 2: In the controller file, get the details of the fiels.
use Illuminate\Support\Facades\Mail;
$name = $request->input('name');
$contact_email = $request->input('contact_email');
$subject = $request->input('subject');
$message = $request->input('message');
$receiver = 'rameshyadavjee@gmail.com';
$details = [
'name' => $name,
'contact_email'=> $contact_email,
'subject' => $subject,
'message' => $message,
'receiver' => $receiver
];
Mail::to($receiver)->send(new \App\Mail\ContactMail($details));
// To use below one use App\Mail\NewRegistrationMail;
//Mail::to($receiver)->send(new NewRegistrationMail($details));
Step 3: Create Blade View
resources/views/email.blade.php
<html>
<head>
<title>New Inquiry</title>
</head>
<body>
<strong>Subject</strong> : {{$_REQUEST['subject']}}<br>
<strong>Name</strong> : {{$_REQUEST['name']}}<br>
<strong>Email</strong> : {{$_REQUEST['contact_email']}}<br>
<strong>Message</strong> : {{$_REQUEST['message']}}
</html>
or
<strong>Subject</strong> : {{$details['subject']}}<br>
<strong>Name</strong> : {{$details['name']}}<br>
<strong>Email</strong> : {{$details['contact_email']}}<br>
<strong>Message</strong> : {{$details['message']}}
That's it
Laravel Telescope
1. composer require laravel/telescope
2. php artisan telescope:install
3. php artisan migrate
4. php artisan vendor:publish --tag=telescope-migrations
5. Prevent the Telescope package from being auto-discovered by adding the following
to your composer.json file:
"extra": {
"laravel": {
"dont-discover": [
"laravel/telescope"
]
}
},
6. If you want to disable Telescope's data collection entirely using the
enabled configuration option:
'enabled' => env('TELESCOPE_ENABLED', true),
7. To run the telesecope use as seen here the url. http://localhost/practise/public/telescope
8. Very important point is open the layout.blade.php from ..\vendor\laravel\telescope\resources\views\layout.blade.php. At the bottom of the file update the code. Practise is my project name.
<script>
window.Telescope = @json($telescopeScriptVariables);
window.Telescope.path = 'practise/public/telescope';
</script>
Note: practise is the project name.
That's it.
Saturday, 5 December 2020
How to create localization in laravel without url changing?
Step 1. Create a route as shown below.
Route::get('en', function() { session(['locale' => 'en']); return back(); });
Route::get('hi', function() { session(['locale' => 'hi']); return back(); });
Step 2. Create a middleware named SetLocale and write the code as below.
php artisan make:middleware SetLocale
<?php
namespace App\Http\Middleware;
use App;
use Closure;
class SetLocale
{
protected $supported_languages = ['en', 'hi'];
public function handle($request, Closure $next)
{
if(!session()->has('locale')) {
session(['locale' => $request->getPreferredLanguage($this->supported_languages)]);
}
app()->setLocale(session('locale'));
return $next($request);
}
}
Step 3. Add the SetLocale middleware in kernal.php
In the protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\SetLocale::class,
Step 4.Update the app.blade for navigation
<ul class="navbar-nav ml-auto">
<!-- Authentication Links -->
@guest
...
@endif
@else
...
@endguest
<li class="nav-item dropdown "> <a class="nav-link
dropdown-toggle"
href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false"> Language </a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item " href="{{url('en')}}">English</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="{{url('hi')}}">Hindi</a> </div>
</li>
</ul>
It will look like this.
Step 5. Create a folder name hi in resources\lang, now create a file named labels.php in hi folder through notepad and set the encoding = UTF-8<?php
return [
];
Now to print the value {{ __('labels.Reset Password') }} or {!! __('labels.Reset Password') !!}
Thanks.
Friday, 4 December 2020
Insert data using database seeder in laravel
php artisan make:seeder AdminsTableSeeder
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class AdminsTableSeeder extends Seeder
{
public function run()
{
DB::table('admins')->insert([
'name' => 'admin',
'email' => 'admin@gmail.com',
'password' => Hash::make('password'),
]);
}
}
composer dump-autoload
Run seeder
php artisan db:seed --class=AdminsTableSeeder
********************************************
To insert multiple record
public function run()
{
DB::table('admins')->insert(array(
array(
'name' => "Steve",
'email' => 'steve@gmail.com',
'password' => Hash::make('secret'),
),
array(
'name' => "Laura",
'email' => 'laura@gmail.com',
'password' => Hash::make('secret'),
)
));
}
********************************************
Insert data using factory in laravel
php artisan make:factory AdminsTableSeeder
<?php
use Faker\Generator as Faker;
use App\Models\Admin;
use Illuminate\Support\Str;
use Hash;
$factory->define(Admin::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' =>$faker->email,
'password' => Hash::make('password'),
];
});
php artisan make:seeder AdminsTableSeeder
<?php
use Illuminate\Database\Seeder;
class AdminsTableSeeder extends Seeder
{
public function run()
{
factory(App\Models\Admin::class, 100)->create();
}
}
php artisan make:seeder AdminsTableSeeder
Thursday, 3 December 2020
Laravel Multi-authentication
php artisan make:migration create_admins_table --create=admins
Put this code in the Admin migration php file
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
run php artisan migrate
Add a record in admins table using seeder.
Next: Create a model name Admin and copy paste below line.
php artisan make:model Models/Admins
Next In the config/auth.php file, set up the custom guards and providers for users and admins.
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
Next step is to create Admin controller
php artisan make:controller Admin\AdminController
class Admincontroller extends Controller {
public function __construct()
{
$this->middleware('auth:admin');
}
public function index() {
return View('admin.dashboard');
}
}
Next step is to create Admin Login Controller
php artisan make:controller Admin\AdminLoginController
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth; use Route;
class AdminLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin', ['except' => ['logout']]);
}
public function showLoginForm()
{
return View('admin.login');
}
public function login(Request $request)
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:4'
]);
// Attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember))
{
// if successful, then redirect to their intended location
return redirect('admin/dashboard');
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
public function logout()
{
Auth::guard('admin')->logout();
return redirect('/admin/login');
}
}
Next Step is Create a new view file with the name admin.login.php for admin
Copy past from login form.
Make sure the <form method="POST" action="{{ route('admin.login') }}"> should be look like this.
Next Step is Create a new view file with the name dashboard.blade.php for admin
This is for laravel 7 . Now we will set our routes; routes/web.php.
Route::prefix('admin')->group(function() {
Route::get('/','Admin\AdminLoginController@showLoginForm')->name('admin.login');
Route::get('/login','Admin\AdminLoginController@showLoginForm')->name('admin.login');
Route::post('/login', 'Admin\AdminLoginController@login')->name('admin.login');
Route::get('logout/', 'Admin\AdminLoginController@logout')->name('admin.logout');
Route::get('/dashboard', 'Admin\AdminController@index')->name('admin.dashboard');
}) ;
This is for laravel 8 . Now we will set our routes; routes/web.php.
Route::get('/', function () { return view('welcome'); });
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::prefix('admin')->group(function () {
Route::get('/',[App\Http\Controllers\Admin\AdminLoginController::class,'showLoginForm'])->name('admin.login');
Route::get('login',[App\Http\Controllers\Admin\AdminLoginController::class,'showLoginForm'])->name('admin.login');
Route::post('login',[App\Http\Controllers\Admin\AdminLoginController::class,'login'])->name('admin.login');
Route::get('dashboard',[App\Http\Controllers\Admin\AdminController::class,'index'])->name('admin.index');
Route::get('logout/', [App\Http\Controllers\Admin\AdminLoginController::class,'logout'])->name('admin.logout');
});
Next step is, we have to set up the different login views for the guards. This in the app/Exceptions/Handler.php
use Illuminate\Support\Arr; use Auth;
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$guard = Arr::get($exception->guards(), 0);
switch ($guard){
case 'admin':
$login = 'admin.login';
break;
default:
$login = 'login';
break;
}
return redirect()->guest(route($login));
}
Next step is If the login is successful, redirect to the dashboard of the specific guard. This is done in the RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null)
{
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.dashboard');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
break;
}
return $next($request);
}
That's it.
Machine Learning - Potato Leaf Disease Prediction
Step 1: import numpy as np import pandas as pd import splitfolders import matplotlib.pyplot as plt import tensorflow as tf from tensorflow i...
-
Step 1. In the env file write the code as below. DB_HOST=127.0.0.1 DB_DATABASE=database1 DB_USERNAME=root DB_PASSWORD= DB_HOST2=127.0.0.1 ...
-
First, install anhskohbo/no-captcha Package for Google reCaptcha code. Using this Package, we can generate reCaptcha code for our Applicat...
