Friday, 22 January 2021

How to get data from following and follower in mysql

 

 

Query 1
SELECT
  `connection`.`person_id`,
  `connection`.`follower_id`,
  `people`.`name`,
  `people`.`age`
FROM
  `test`.`people`
  INNER JOIN `test`.`connection`
    ON (
      `people`.`id` = `connection`.`follower_id`
    )
WHERE (`connection`.`person_id` = 3);

Query 2
SELECT person_id, GROUP_CONCAT(DISTINCT follower_id SEPARATOR ', ') AS follower
FROM CONNECTION GROUP BY person_id

Query 3
SELECT person_id, GROUP_CONCAT(DISTINCT follower_id SEPARATOR ', ') AS follower
FROM CONNECTION WHERE (`connection`.`person_id` = 3)
GROUP BY person_id

Query 4
SELECT DISTINCT f.person_id,
o.following,
e.follower
FROM CONNECTION f
LEFT JOIN
(
    SELECT CONNECTION.person_id, GROUP_CONCAT(DISTINCT follower_id SEPARATOR ', ') AS following
    FROM CONNECTION GROUP BY person_id
) AS o ON f.person_id = o.person_id
LEFT JOIN
(
    SELECT CONNECTION.follower_id, GROUP_CONCAT(DISTINCT person_id SEPARATOR ', ') AS follower
    FROM CONNECTION GROUP BY follower_id
) AS e ON f.person_id = e.follower_id

 

Monday, 11 January 2021

Git command

git init
git clone https://github.com/rameshyadavjee/laravel.git
git branch temp
git checkout temp
git add *
git commit –m "Message to go with the commit here"
git config --local user.email rameshyadavjee@gmail.com
git remote add origin https://github.com/rameshyadavjee/laravel.git
git push origin master

 

Run the below code

ssh-keygen
Enter
Enter
Enter

Got to profile and search .ssh   // Example C:\Users\KRISHNA\.ssh

Open the file id_rsa.pub
Copy the content and

https://github.com/settings/keys
Click on New SSH Key
Paste the content

Thats it

How to get last insert id?

 In laravel, when you go with DB query builder then you can use insertGetId() that will insert a record and then return last inserted record id.
Example:
 
        $id = DB::table('users')->insertGetId(
                ['email' => 'rameshyadavjee@gmail.com', 'name' => 'Ramesh']
        );
        print_r($id);
   

If you are inserting a record using Laravel Eloquent then you don't need to use insertGetId() function to get last inserted id. You can simply use create method to insert a new record into. The inserted model instance will be returned to you from the method.
Example:


        $user = User::create(['name'=>'Ramesh','email'=>'rameshyadavjee@gmail.com']);
        print_r($user->id);
 

What is traits?

Traits are a mechanism for code reuse in single inheritance languages such as PHP. Write the same code again, to avoid this use the traits. The traits are used when multiple classes share the same functionality.

Here is an example of trait.

<?php
namespace App\Http\Traits;
use App\Models\Users;

trait UserTrait {
    public function userdata() {
        // Fetch all the user from the 'user' table.
        $user = User::all();
        return $user;
    }
}

************************************************

use App\Http\Traits\UserTrait;

class .....
{
    use UserTrait;
    public function ()
    {
        $data = $this->userdata();
        we will get the data in $data variable.
    }
}


Check if Table/Column Already Exists

Check if Table/Column Already Exists


public function up()
{
  if (!Schema::hasTable('vendor')) {
    Schema::create('vendor', function (Blueprint $table) {
      $table->increments('id');
      $table->string('name');      
      $table->timestamps();
    });
  }
}

public function up()
{
  if (Schema::hasTable('vendor')) {
    Schema::table('vendor', function (Blueprint $table) {
      if (!Schema::hasColumn('vendor', 'address')) {
        $table->string('address');
      }
    });
  }
}

What is Chunk and Cursor?

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

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

Cover image for Laravel Request Lifecycle
 

 

 

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

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