Laravel 8 Tips 1

 


-- Laravel Debugbar
    Source: https://github.com/barryvdh/laravel-debugbar
-- Specified key was too long; max key length is 767 bytes

..\app\Providers\AppServiceProvider.php
    use Illuminate\Support\Facades\Schema;
    public function boot() {
        Schema::defaultStringLength(190); 
    }

-- Row Single Data

    $sqlData = collect(DB::select("SELECT * FROM pickup_from WHERE id         = 334"))->first();

    dd($sqlData->loading_destination_name);

-- 100 (and counting) Laravel Quick Tips
Source: laraveldaily.com
File URL: https://app.box.com/s/hmcr9pplvooctuhpd04bj978hwiqyrvc
-- Laravel debug:
1. dd($variable);
2. dump($variable);

-- get() is used when you want to add queries and all() is used to get all data, without using any condition.
1. $query = Project::all();
2. $getFlightModel = Flight::get();
3. $query = Project::select('id', 'name')->where('name', '')->orderBy('id', 'desc')->get();
foreach ($getFlightModel as $value) {
dump($value->title);
dump($value['title']);
}

-- env and config file data access
$appName = env('APP_NAME');
        $configAppName = config('app.name');
        dd($appName,$configAppName);

-- blade 
Displaying Unescaped Data
1. Hello, {!! $name !!}.

-- Laravel - Controller - Dynamic Menu - All Pages
In AppServiceProvider.php class edit boot method
use Illuminate\Support\Facades\View;
public function boot()
{
$categories = Categorias::where([
['exibir', '=', 1],
['publicado', '=', 1]
])
->get();

View::composer('*', function ($view) {
$view->with(['mainMenu' => 'categories']);
});
}
Also you can use all power of laravel
public function boot()
{
$mainMenu = Categorias::whereWxibir(1)
->wherePublicado(1)
->get();

View::composer('*', function ($view) {
$view->with(compact('mainMenu'));
});
}

-- What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()
1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.
2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.
3. first() returns the first record found in the database. If no matching model exist, it returns null.
4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.
5. get() returns a collection of models matching the query.
6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.
7. toArray() converts the model/collection into a simple PHP array.

-- HTTP Client
Source: https://laravel.com/docs/8.x/http-client
-- Route
Route::get('/flight-list/{flight_type?}', [FlightController::class, 'index'])->name('flight.list');

    Route::fallback(function(){
        return 'Page Not Found 404';
    });

FlightController
public function index(Request $request, $flight_type="booked") {
}
Blade
<a href="{{ route('flight-list',['flight_type'=>$model->flight_type]) }}">Flight Type</a>
-- Component
class Alert extends Component
{
public $type;
public $info;
public function __construct($type, $info)
{
$this->type = $type;
$this->info = $info;
}
public function render()
{
return view('components.alert');
}
public function list($item) {
return [
'I',
'Ram',
'Pukar',
'Chaudhary',
$item,
];
}
}

component alert.blade file.
<div>
I begin to speak only when I am certain what I will say is not better left unsaid. - Cato the Younger <br/>
{{ $type }}<br/>
information {{ $info }}<br/>
<ul>
@foreach ($list('KTM') as  $value)
{{ $value }}
@endforeach
</ul>
</div>

dashboard.blade.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Laravel Cloud</title>
</head>
<body>
<x-alert type="Sr. Developer" :info="$info"/>
</body>
</html>

flight.blade.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Laravel Cloud</title>
</head>
<body>
<x-alert type="Sr. Developer" :info="$info"/>
</body>
</html>
--Conditional Classes
<body>
@php
$isActive = true;
@endphp
<div class="container">
<button @class([
'btn btn-sm' ,
'btn-primary'=>$isActive,
])>STATUS</button>   
</div>
</body>
-- PHP - What are Traits?
PHP only supports single inheritance: a child class can inherit only from one single parent.So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem. Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).
Traits are declared with the trait keyword:

<?php
namespace App\Http\Controllers;
use App\Models\Flight;
use Illuminate\Http\Request;

trait Booking {

public static $ROLE_TYPE = [
        'admin'=>'Admin',
        'normal'=>'Normal',
        'advance'=>'Advance',
    ];

    public function hotelBook() {
        echo "This Hotel Booking <br/>";
    }
}
trait House {
    public function houseName() {
        echo "My house name Google<br/>";
    }
}
class FlightController extends Controller
{
    use Booking, House;
    public function index()
    {
        $this->hotelBook();
        $this->houseName();
        dump($this::$ROLE_TYPE);
        dd('done');
        $passData['info'] = 'Very good information!66666';
        return view('flight',$passData);
    }
}
OUTPUT:

    This Hotel Booking
    My house name Google
    array:3 [
      "admin" => "Admin"
      "normal" => "Normal"
      "advance" => "Advance"
    ]

    "done"

-- Immutable
Model
class Flight extends Model{
use HasFactory;
protected $guarded = [];
protected $casts = [
'created_at' => 'immutable_datetime'
];

}
Controller

flightModel = Flight::find(1);
$createdDate = $flightModel->created_at;
dd($createdDate->addDays(5));
Blade
@foreach ($flightModel as $flight)
{{ $flight->created_at }} => {{ $flight->created_at->addDays(5) }}<br/>
@endforeach

-- Abort (if record is exist other wise show abort 403 code)
$flightModel = Flight::where('id',6)->firstOr(fn () => abort(403));
or
$flightModel = Flight::where('id',6)->firstOr(function(){
abort(403);
});

-- Available Router Methods

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

Route::match(['get', 'post'], '/', function () {
//
});
Route::any('/', function () {
//
});

-- ROUTE TIPS
Retrieving The Request Method

$method = $request->method();
if ($request->isMethod('post')) {
}
-- Retrieving The Request Path
$uri = $request->path();
$urlWithQueryString = $request->fullUrl()
$request->fullUrlWithQuery(['type' => 'phone'])
dump($contentTypes = $request->getAcceptableContentTypes());
if ($request->accepts(['text/html', 'application/json'])) {
echo "done";
}
dump($preferred = $request->prefers(['text/html', 'application/json']));
dump($request->expectsJson());

Output:
"cargo-detail/68"
"http://sku-cargo-v1.local.com/cargo-detail/68"
"http://sku-cargo-v1.local.com/cargo-detail/68?type=phone"
array:8 [
  0 => "text/html"
  1 => "application/xhtml+xml"
  2 => "image/avif"
  3 => "image/webp"
  4 => "image/apng"
  5 => "application/xml"
  6 => "application/signed-exchange"
  7 => "*/*"
]
done
"text/html"
false
-- Retrieving An Input Value
dd($input = $request->collect());
dd($getEmail = $request->input('email', 'example@gmail.com'));

-- Model Where and OrWhere clause
$flightModel = Flight::where(['ref_record_id'=>$id,'delete_flg'=>0])->where(function($query) {
$query->where('category_type','images')
->orWhere('category_type','docs');
})->get();
SQL Output:
select * from "flight" where ("ref_record_id" = '118' and "delete_flg" = 0) and ("category_type" = 'images' or "category_type" = 'docs')

-- BLADE
header.blade.php
-------------------
<!DOCTYPE html>
<html>
<head>
<title>@yield('title', 'Default Content')</title>
<link rel="stylesheet" type="text/css" href="{{asset('css/bootstrap.min.css')}}">
</head>
<body>
@yield('content')
</body>
</html>
nav.blade.php
------------------------------
<a href="">Home</a> || 
<a href="">About</a> ||
<a href="">Help</a>

index.blade.php
-----------------------------
@extends('layouts.header')
@section('title','About Us')
@include('layouts.nav')
@section('content')
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
@endsection
***********************************************************
@parent
Hello, {{ $name }}.
The current UNIX timestamp is {{ time() }}.
{{ isset($name) ? $name : 'Default' }}
{{ $name or 'Default' }}
***********************************************************
@{{ This will not be processed by Blade }}
Output:
{{ This will not be processed by Blade }}
***********************************************************
CKEditor Type 
Hello, {!! $name !!}
***********************************************************
@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif
@unless (Auth::check())
    You are not signed in.
@endunless
***********************************************************
Loops
@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor
@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach
@forelse($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse
@while (true)
    <p>I'm looping forever.</p>
@endwhile
***********************************************************
Including Sub-Views
@include('view.name')
@include('view.name', ['some' => 'data'])
***********************************************************
Overwriting Sections
@extends('list.item.container')
@section('list.item.content')
    <p>This is an item of type {{ $item->type }}</p>
@overwrite
***********************************************************
Displaying Language Lines
@lang('language.line')
@choice('language.line', 1)
***********************************************************
Comments
{{-- This comment will not be in the rendered HTML --}}
-- Error Message
@if ($errors->any())
{{ dd($errors->all()) }}
@endif

Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment