get current year in laravel query builder

$data= array();     
              $data = DB::connection($lang)->table('cal_image_calendar')->where('status','1')->where('year',$year)->get();//->toJson(JSON_PRETTY_PRINT);   
              //return response($data, 200);   
              return $this->sendResponse($data, 'Successfully');

get last inserted row id in laravel query builder

$id = DB::table('users')->insertGetId(
    [ 'name' => 'first' ]
);

dd($id);
DB::table('users')->insert([
    'name' => 'TestName'
]);
$id = DB::getPdo()->lastInsertId();;
dd($id);

language value print in Laravel blade

<?php

// resources/lang/en/messages.php

return [
    'welcome' => 'Welcome to our application!',
];
echo __('messages.welcome');
{{ __('messages.welcome') }}

@lang('messages.welcome')

Laravel language file contains array



<?php

// resources/lang/en/messages.php

return [
  'month'=>array("जनवरी","फरवरी","मार्च","अप्रैल","मई","जून","जुलाई","अगस्त","सितम्बर","अक्टूबर","नवम्बर","दिसम्बर"),
];

{{ __('message.month.1') }}

two table column display in single query Laravel 8 | nested query in Laravel

Joins in Laravel

Inner Join Clause

The query builder may also be used to add join clauses to your queries. To perform a basic “inner join”, you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. You may even join multiple tables in a single query:

use Illuminate\Support\Facades\DB;

$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();

Left Join / Right Join Clause

If you would like to perform a “left join” or “right join” instead of an “inner join”, use the leftJoin or rightJoin methods. These methods have the same signature as the join method:

$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();

$users = DB::table('users')
            ->rightJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();

Cross Join Clause

You may use the crossJoin method to perform a “cross join”. Cross joins generate a cartesian product between the first table and the joined table:

$sizes = DB::table('sizes')
            ->crossJoin('colors')
            ->get();

Advanced Join Clauses

You may also specify more advanced join clauses. To get started, pass a closure as the second argument to the join method. The closure will receive a Illuminate\Database\Query\JoinClause instance which allows you to specify constraints on the “join” clause:

DB::table('users')
        ->join('contacts', function ($join) {
            $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
        })
        ->get();

If you would like to use a “where” clause on your joins, you may use the where and orWhere methods provided by the JoinClause instance. Instead of comparing two columns, these methods will compare the column against a value:

DB::table('users')
        ->join('contacts', function ($join) {
            $join->on('users.id', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '>', 5);
        })
        ->get();

Subquery Joins

You may use the joinSubleftJoinSub, and rightJoinSub methods to join a query to a subquery. Each of these methods receives three arguments: the subquery, its table alias, and a closure that defines the related columns. In this example, we will retrieve a collection of users where each user record also contains the created_at timestamp of the user’s most recently published blog post:

$latestPosts = DB::table('posts')
                   ->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
                   ->where('is_published', true)
                   ->groupBy('user_id');

$users = DB::table('users')
        ->joinSub($latestPosts, 'latest_posts', function ($join) {
            $join->on('users.id', '=', 'latest_posts.user_id');
        })->get();

optional argument in Laravel route

Occasionally you may need to specify a route parameter that may not always be present in the URI. You may do so by placing a ? mark after the parameter name. Make sure to give the route’s corresponding variable a default value:

Route::get('/user/{name?}', function ($name = null) {
    return $name;
});

Route::get('/user/{name?}', function ($name = 'John') {
    return $name;
});

group by with like in laravel 8

$results = User::select(\DB::raw('YEAR(date) as year, COUNT(id) as amount'))
    ->groupBy(\DB::raw('YEAR(date)'))
    ->get();

So, we’re using DB::raw() for all select statement, also repeating the same condition in groupBy(). Here’s the visual result for my dummy seeded data:

set timezone in laravel 8

edit file /config/app.php and change value of timezone

'timezone' => 'Asia/Dhaka'

Using Environment file (.env)

Inside env
add DB config
DB_TIMEZONE=+08:00

Laravel seo hack trick

header.blade.php

  <!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">


    @yield('seo')


    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
{{-- san San-Francisco Font --}}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/mailtoharshit/San-Francisco-Font-/sanfrancisco.css">
  <link rel="stylesheet" href="{{ asset('/index.css') }}">
  

    <!-- <link rel="stylesheet" href="{{ asset('/homejs.js') }}"> -->
    <title>Aditya Kumar Singh</title>
  </head>
  <body>
  <nav class="navbar navbar-expand-lg navbar-red navbar-dark p-0">
    <!-- <div class="wrapper"> </div> -->
    <div class="container-fluid"> <a class="navbar-brand p-0" href="/">
     
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto ml-auto">

                <li class="nav-item"> <a class="nav-link mr-4 " aria-current="page" href="/">Home</a> </li>
                <!-- <li class="nav-item"> <a class="nav-link mr-4" href="#">Features</a> </li> -->
                <li class="nav-item"> <a class="nav-link mr-4" href="/about" call_type="About">About us</a> </li>
                <!-- <li class="nav-item"> <a class="nav-link mr-4" href="#">Fees</a> </li> -->
                <li class="nav-item"> <a class="nav-link mr-4" href="/contact" call_type="Contact">contact us</a> </li>
                <!-- <li class="nav-item"> <a class="nav-link mr-4" href="#"><i class="fa fa-search"></i></a> </li> -->
            </ul>
            <!-- <div class="d-flex flex-column sim"> <a class="btn btn-light action-button" role="button" href="#">Sign Up <i class="fa fa-arrow-right"></i></a> </div> -->
        </div>
    </div>
</nav>
   
  @yield('content') 
  @yield('footer')

index.blade.php

@extends('header')
@section('seo')
<title>Aditya kumar singh</title>
<meta name="description" content="aditya kumar singh">
<meta name=”robots” content="index, follow">
@endsection
  @section('content') 


<!-- HTML TAG -->

@endsection
@extends('footer')

contact.blade.php

@extends('header')
@section('seo')
<title>Aditya kumar singh</title>
<meta name="description" content="aditya kumar singh">
<meta name=”robots” content="index, follow">
@endsection
  @section('content') 
  <section id="contact" style="background-color:#f5f5f5">
<div class="container py-5">
	<div class="row justify-content-center align-items-center">
		<div class="col-12 col-sm-12 col-md-10 col-lg-10">
    
      <form action="/add-contact " method="post">
      @csrf
      <div class="text-center py-4"><h3 class="display-4 bold orange">Contact Us</h3>
                                </div>
                                @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif
                                <div class="row" style="margin:0px 0px">
                                <div class="col-lg-6 col-md-6 col-sm-6" style="padding-bottom: 10px;">
                                <label for="name" class="mb-2"><b>Name</b></label>
                                <input class="form-control shadow p-4 mb-4 bg-white rounded @error('name') is-invalid @enderror" name="name" placeholder="Marth Wanjiku" type="text" />
                                @error('name')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
@enderror
  </div>
                                <div class="col-lg-6 col-md-6 col-sm-6" style="padding-bottom: 10px;">
                                <label for="email" class="mb-2"><b>Email</b></label> 
                                 <input class="form-control shadow p-4 mb-4 bg-white rounded @error('email') is-invalid @enderror" name="email" placeholder="what's your email?" type="text"  />
                                 @error('email')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
@enderror
   </div>
                                </div>
                                <div class="col-lg-12 col-md-12 col-sm-12" style="padding-bottom: 10px;">
                                <label for="msg" class="mb-2"><b>Massage</b></label>
                                <textarea rows="6" name="message" id="message2" class="form-control shadow p-4 mb-4 bg-white rounded @error('message') is-invalid @enderror" placeholder="How Can Help You?" ></textarea> 
                                @error('message')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
@enderror
   </div>
                                <div class="btn-left">
                                   <input type="submit" name="sent" value="SUBMIT" class="btn btn-info btn-block rounded-0 py-2">
                                </div>
</div>
                    </form>
	  </div>
  </div>
</div>
</section>

  @endsection
@extends('footer')

Laravel 8 migrate specific table

php artisan migrate --path=/database/migrations/fileName.php
php artisan migrate --path=/database/migrations/2020_04_10_130703_create_test_table.php
php artisan migrate:refresh --path=/database/migrations/2021_06_23_093317_create_users_table.php
To rollback one step:

php artisan migrate:rollback

To rollback multiple steps:

php artisan migrate:rollback --step=[x]
  
To drop all tables and reload all migrations:

php artisan migrate:fresh

Laravel database migrate command

php artisan migrate
php artisan migrate:fresh
php artisan migrate:install
php artisan migrate:refresh
php artisan migrate:reset
php artisan migrate:rollback
php artisan migrate:status