Php, Laravel
Title | Code |
---|---|
|
<?php $sql="select*from child"; $result=mysqli_query($conn,$sql); ?> <h1 class="text-center mb">User information</h1> <table class="table" border="1"> <thead> <th>Id</th> <th>Name</th> </thead> <tbody> <?php while ($row=mysqli_fetch_assoc($result)) { ?> <tr> <td><?php echo $row['id'];?></td> <td><?php echo $row['name'];?></td> </tr> <td> <a class="btn btn-info" href="view.php?id=<?php echo $row['id']; ?>">View</a> <a class="btn btn-danger" onclick="return confirm('Are you sure?')" href="delete.php?id=<?php echo $row['id']; ?>">Delete</a> </td> <?php } ?> </tbody> </table> |
|
(1st part) ex: edit.php header("Location: index.php?success=1"); <a class="btn btn-info" href="view.php?success=1"> $_SESSION['success']=1; //true NB: number not mandatory (2nd part...) <div class="col-md-9"> <?php if(isset($_GET['success'])) { ?> <div class="alert alert-success"> <strong>Success!</strong> Added successfully. </div> <?php } ?> </div> session_start(); <div class="col-md-9"> <?php if(isset($_SESSION['success'])) { ?> <div class="alert alert-success"> <strong>Success!</strong> Added successfully. </div> <?php } ?> </div> unset($_SESSION['success']); NB: alert list success, danger, info, warning CSS: .alert { padding: 20px; background-color: #f44336; color: white; } <a href="index.php" class="confirmation"></a> <script> $('.confirmation').on('click', function () { return confirm('Are you sure?'); }); </script> <a class="btn btn-danger btn-fill pull-center" onclick="return confir |
|
<?php $sql="select*from child where id=$id"; $result=mysqli_query($conn,$sql); $row=mysqli_fetch_assoc($result); ?> <table class="table"> <tr> <th width="100" class="text-right">Name : </th> <td class="text-left"> <?= $row['name']; ?></td> </tr> <tr> <th width="100" class="text-right">Roll : </th> <td class="text-left"> <?= $row['roll']; ?> </td> </tr> <tr> <th width="100" class="text-right">Age : </th> <td class="text-left"> <?= $row['age']; ?> </td> </tr> </table> |
|
<?php $id= $_GET['id']; $conn=connectDB(); $sql="select*from child where id=$id"; $result=mysqli_query($conn,$sql); $row=mysqli_fetch_assoc($result); ?> <h2>Edit Student</h2> <form action="update.php?id=<?php echo $id ?>" method="POST"> <div class="form-group"> <label for="name">Name: </label> <input type="text" class="form-control" name="" placeholder="" value="<?= $row['name']; ?>" > </div> <div class="form-group"> <label>Roll: </label> <input type="text" class="form-control" name="" placeholder="" value="<?= $row['roll']; ?>"> </div> <div class="form-group"> <label>Age: </label> <input type="text" class="form-control" name="" placeholder="" value="<?= $row['age']; ?>"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> |
|
laravel: 5.9 last php artisan make:auth laravel: 6.0 composer require laravel/ui php artisan ui vue --auth laravel: 7.0 composer require laravel/ui:^2.4 php artisan ui vue --auth laravel: 9 composer require laravel/ui php artisan ui bootstrap php artisan ui bootstrap --auth |
|
1) create only database name in phpmysql 2) In project select [.env] see line no 9-14 change it DB_DATABASE=DB Name DB_USERNAME=root DB_PASSWORD= 3) Restart [php artisan serve] Off (Ctrl+C) then On 1st time Go app/Providers/AppServiceProvider write: use IlluminateSupportFacadesSchema; [line 6] Schema::defaultStringLength(191); [function booth line 26] php artisan migrate php artisan migrate:status [see create database] php artisan migrate:rollback [remove data from database] php artisan migrate:refresh or fresh [remove data then create database] |
|
edit your AppServiceProvider.php file and inside the boot method set a default string length: use IlluminateSupportFacadesSchema; public function boot() { Schema::defaultStringLength(191); } app/Providers/AppServiceProvider write: use IlluminateSupportFacadesSchema; [line 6] Schema::defaultStringLength(191); [function booth line 26] |
|
Controller: return back()->with('status', 'Product insert successfully'); page.blade.php: @if (session('status')) <div class="alert alert-success" role="alert"> {{ session('status') }} </div> @endif |
|
create model $php artisan make:model Model_name -m migrate $ php artisan migrate create controller $ php artisan make:controller Controller_name model, controler, migration all $php artisan make:model Category -mc Output all and also controller seen like CategoryController but we put only Category |
|
https://carbon.nesbot.com/docs/ //All time zone set [go config/app.config/line no 70] 'timezone' => 'UTC', to 'timezone' => 'Asia/Dhaka', php artisan config:clear Controller: Carbon::now('Asia/Dhaka') Blade: {{ $category->created_at->diffForHumans() }} |
|
@php $menus=App\Category::latest()->take(5)->get(); @endphp @foreach ($menus as $menu) {{$menu->category_name}} @endforeach Output: Now show the latest five(5) category name |
|
suppose your page location: 'contact' page blog ---->views ----->layouts --->home --->about --->contact My present location 'contact' page and a action page working now 1) return view('layouts/contact', compact('something')); N:B: session with() not allow 2) return redirect(contact)->with('status', 'message allow'); N:B: session with() allow 3) return back()->with('status', 'message allow'); N:B: session with() allow Session: withStatus('Message send successfully!); same meaning but 'status' should capital letter @if (session('status')) <div class="alert alert-success" role="alert"> {{ session('status') }} </div> @endif |
|
link: https://www.youtube.com/watch?v=iQoRh_9LkjU video :9 duration: 33:55 https://laravel.com/docs/5.8/mail #Driver Prerequisites composer require guzzlehttp/guzzle #generating-mailables php artisan make:mail OrderShipped N:B: Sometime it don't work when compact send the variable file. So it is better to follow video link |
|
@php error_reporting(0); @endphp |
|
Hello friends... Today I am going to show how to run github laravel projects. link: https://www.youtube.com/watch?v=ngzOHoyITfM 1. download the laravel project from github. 2. copy that project in hotdocs folder and open the folder location in cmd. 3. now first rename the "env.example file to.env" 4. you can configure the database information here. 5. now open cmd and run some commands... composer install or php composer.phar install php artisan key:generate php artisan migrate php artisan db:seed to run seeders, if any. php artisan serve that's all.. Problems discussion:: you may have the problem with the composer or the php... check all are installed.. and the paths are added as the environment variable... These two paths have to be added to run laravel project... 1. C:ProgramDataComposerSetupin 2. C:xamppphp if these are not added.. then add them .. thank you very much for watching... Please subscribe and share...:) Categ |
|
[video 6 [00.20.00]] http://image.intervention.io/getting_started/installation 1st step: $composer require intervention/image 2nd step: go-> config/app.php search-> $providers [array] paste: Intervention\Image\ImageServiceProvider::class, search-> $aliases [array] 'Image' => Intervention\Image\Facades\Image::class, 3rd step: use Image; function insert_product(Request $request) { //this part not need for image upload... $last_inserted_id = Product::insertGetId([ 'category_id'=>$request->category_id, 'name'=>$request->name ]); if ($request->hasFile('product_image')) { //please link image upper... use Image; $photo_to_upload=$request->product_image; $fileName=$last_inserted_id.".".$photo_to_upload->getClientOriginalExtension(); Image::make($photo_to_upload)->resize(400,380) ->save(base_path('public/Full_Project/images/product_images/'.$fileName)); //Image quality save(ba |
|
https://www.youtube.com/watch?v=e7eSJCevo4c |
|
https://scotch.io/tutorials/simple-laravel-layouts-using-blade |
|
<td> {{ $SingerList->DOB}} <br> {{\Carbon\Carbon::parse($SingerList->DOB) ->diff(\Carbon\Carbon::now()) ->format('%y years, %m months and %d days')}} </td> Example: Input: 1994-08-06 Output: 1994-08-06 25 years, 5 months and 16 days |
|
Note : GET method 1) blade.php <form action="{{ url('all_singerName')}}" method="get"> <input type="text" name="singerName" value="{{ old('singerName')}}" class="form-control" placeholder="Name"> <button class="btn btn-success btn-block" type="submit">Add Now</button> </form> 2) web.php Route::get('all_singerName', 'Singer@all_singerName'); 3) public function all_singerName(Request $request){ $email = Auth::user()->email; $singerName = $request->singerName; {{-- 1st way input --}} $all_songs = AllSong::where('email', $email)->where('singerName', $singerName)->paginate(5); {{-- 2nd way input --}} $all_songs = AllSong::where('email', 'Like', '%'.$email.'%')->where('singerName', 'Like', '%'.$singerName.'%')->paginate(5); $all_songs->appends($request->only('singerName')); //get request return view('singerName', compact('all_songs')); } 4) Output <div class="card-body"> <table class="table"> <tr class="text-center"> <th>Sl. No</th> <th>Song name</th> </tr> </thead> <tbody> @forelse($all_songs as $all_song) <tr class="text-center"> <td>{{$loop->index + $all_songs->firstItem()}}</td> <td>{{ $all_song->songName}}</td> </tr> @empty <tr class="text-center text-danger"> <td colspan="2">No data found...</td> </tr> @endforelse </tbody> </table> {{-- 1st way input --}} {{$all_songs->appends($_GET)->links()}} {{-- 2nd way input --}} {{$all_songs->links()}} Or {{$all_songs->appends($_GET)->links()}} </div> |
|
MAIL_DRIVER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=587 MAIL_USERNAME=aslamhossainctg@gmail.com MAIL_PASSWORD=swnwfctznnjruscc MAIL_ENCRYPTION=tls |
|
<td> {{ $category->created_at->format('d-M-Y h:i:s A')}} {{ date('Y-m-d h:i A', strtotime($category->created_at)) }} <br> {{ $category->created_at->diffForHumans()}} </td> date age {{\Carbon\Carbon::parse($SingerList->DOB)->diff(\Carbon\Carbon::now())->format(' %y years ')}} {{ \Carbon\Carbon::parse($Song->created_at)->diffForHumans() }} |
|
@foreach(range(date('Y')-5, date('Y')) as $y) {{$y}} @endforeach output: 2015 2016 2017 2018 2019 2020 |
|
https://www.youtube.com/watch?v=xBFPGTle7nU cmd C:\Users\Aslam>cd C:\xampp\htdocs\folderName dir ren .env.example .env |
|
https://artisansweb.net/use-laravel-tinker/ composer require laravel/tinker php artisan make:model Product php artisan tinker $p = new App\Product; $p->name = 'Test Product'; $p->description = 'Test Product Body'; $p->password = Hash::make(12345678) $p->save(); Output: $a = new App\user; $a = \App\user::first(); => App\User { id: 1, name: "aslam2", email: "admin@admin.com", email_verified_at: null, created_at: "2020-07-15 15:47:09", updated_at: "2020-07-15 15:47:09", } |
|
date_default_timezone_set("Asia/Dhaka"); $today= date("Y-m-d-D"); $lastDay = date ("Y-m-d", strtotime("-1 day", strtotime($today))); $lastMonth = date ("Y-m-d", strtotime("-1 month", strtotime($today))); $NextYear = date ("Y-m-d", strtotime("1 year", strtotime($today))); $todayday = date('l', strtotime($today)); small [L] Ex: saturday, sunday etc... $day = date('d', strtotime($lastMonth)); $month = date('m', strtotime($lastMonth)); $year = date('Y', strtotime($lastMonth)); Time //Example Y-m-d H:i:s date string. $date = '2019-02-15 16:56:01'; //12 hour format with lowercase AM/PM echo date("g:ia", strtotime($date)) echo date("h:ia", strtotime($date)) Ex: g= 05=5 without zero h=05=05 full a= small am/pm A=capital AM/PM $total=strtotime($end_time) - strtotime(date("H:i:s")); $minute=$total/60; $total=$minute/60; Different two date $startdate->diff($endDate)->format('%y years, %m months and %d days') |
|
input 1: $conn <?php function connectDB() { $conn =mysqli_connect('localhost','root','','bazar'); return $conn; } ?> NB: server, user name, pass, db name Call this function <?php $code = conn() ;?> input 2: $result <?php $conn=connectDB(); $sql="select*from userinfo"; $result=mysqli_query($conn,$sql); return $result; ?> |
|
session_start(); $_SESSION['adminLogin']=true; $_SESSION['login']=$admin; unset($_SESSION['id_pass_fail']); /*logout*/ session_start(); session_destroy(); <?php $_SESSION['successfully']=true; ?> <?php if(isset($_SESSION['successfully'])) { ?> <?php if (isset($_GET['type'])) { $code_type = $_GET['type']; } echo '<script type="text/javascript"> alert("Hellow [ '.$code_type.' ] code insert successfully."); </script>'; ?> <?php } ?> |
|
<?php include('connection.php'); ?> |
|
<?php header("Location: index.php?id=$id"); ?> <a href="index.php?id=$id"></a> echo "<script>window.location.href='index.php?id=$id'</script>"; $id= $_GET['id']; |
|
session_start(); if(!isset($_SESSION['login'])){ header("location: index.php"); } if(isset($_SESSION['login'])){ header("location: about.php"); } |
|
(1st page) ex: login.php up page: <?php session_start(); ?> .............. .............. (2nd page) ex: confirmLogin.php $email=$_POST['email']; $pass=$_POST['password']; $sql="select * from admin where email='$email' AND password='$pass'"; $rowcount=mysqli_num_rows($result); if($rowcount==1) { $_SESSION['login']=true; header("Location: index.php"); } else { ...................... ...................... (3rd page) ex: index.php up page: <?php session_start(); if(!isset($_SESSION['login'])){ header("Location: login.php"); } (4th page) ex:logout.php <?php session_start(); session_destroy(); header("Location: login.php"); |
|
<a href="view.php" class="btn btn-default"> <?= substr($row['description'], 0, 80) . '...' ?> </a> |
|
(2nd page ) <?php $name=$_POST['name']; $pass=$_POST['pass']; $conPass=$_Post['con_pass']; if($pass !=$conPass) { session_start(); $_SESSION['error_msg']="password and confirm Password don't match"; heade("Location: registration.php"); ?> $con=..... $sql="insert into ...."; (1st page registration.php) <?php if(isset($_SESSION['error_msg'])) { ?> <div class="alert alert-warning"> <strong>Warning!</strong> <?php echo $_SESSION['error_msg']; ?> </div> <?php } ?> |
|
<?php $url='http://localhost/class/blog/admin/'; ?> <a href="<?php echo $url; ?> post/index.php"> Post </a> |
|
image is (varchar(150)) (1st page) <form action="store.php" enctype="multipart/form-data" method="POST"> <label for="image">Image</lable> <input type="file" name="president_photo"> </form> (2nd) N:B: "upload" folder will be root position $president_photo='profile_picture/'. $_FILES['president_photo']['name']; move_uploaded_file($_FILES['president_photo']['tmp_name'],$president_photo); $sql= "insert.... (null, $president_photo); (3rd index.php) image show when click the "view" button <img src="<?php echo $row['image']; ?>" width='100'> (4th) click 'delete' button $id=$_GET['id']; $sql="select*from posts where id=$id'"; $data=mysqli_fetch_assoc($reslt); $image_location='$data['image']; if(file_exists($image_location)){ unlink($image_location);=> for image delete code(unlink) } $sql="delete*from posts where id=$id'"; $result; header ('Location: index.php'); if(file_exists($image_location)){ echo "File have"; }else{ echo "don't have"; } |
|
$_age = floor((time() - strtotime('1986-09-16')) / 31556926); 31556926 is the number of seconds in a year. [365*24*60*60] |
|
use Illuminate\Support\Str; echo Str::random(10); echo time()."<br>"; echo microtime(true)."<br>"; echo uniqid()."<br>"; echo rand()."<br>"; echo rand(2,50)."<br>"; $uniqid = uniqid(); $rand_start = rand(1,5); $rand_8_char = substr($uniqid,$rand_start,8); echo '<script type="text/javascript"> alert("See Logic: Result will be 8 digit: Full: '.$uniqid.' Distance: '.$rand_start.' Result: '.$rand_8_char.'"); </script>'; |
|
$search = array("_", "-", "A"); $replace = array("/", "_", "a"); $target='A_s-lAm'; $result=str_replace($search, $replace, $dob.$today); echo $result; input A_s-lAm Output a/slam |
|
Time to time minus or plus $total=strtotime("12:10") - strtotime("12:00"); Ans: 600 only time: $total=strtotime("10:10"); ans: 1564373400 because it convert to year from now then convert to second So u should convert it... $total=strtotime("10:10") - strtotime("09:00"); ans:4200 $total=strtotime("10:10") - strtotime("00:00"); ans:36600 [10h*60m + 10=610m*60s=36600s] |
|
// Only page name //Smart way echo basename($_SERVER['PHP_SELF']); Output: page.php // Old way $folder = "/job/"; $link = $_SERVER['PHP_SELF']; Output: /job/page.php $page = str_replace($folder, "", $link); Output: page.php Suppose my server URL now.... http://localhost/job/page.php?id=1 php code... 1) echo $_SERVER['PHP_SELF']; Output: /job/page.php 2) echo $_SERVER['SERVER_NAME']; Output: localhost 3) echo $_SERVER['REQUEST_URI']; Output: /job/page.php?id=1 So if i want full URL i can use 1) echo $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']; Output: localhost/job/page.php 2) echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; Output: localhost/job/page.php?id=1 3) Full URL $_SERVER['SCRIPT_FILENAME']; Output: E:/laragon/www/job/page.php?id=1 4) After all $from = $_SERVER['REQUEST_URI']; $to = $_SERVER['PHP_SELF']; $goTo = str_replace($from, $to, $from); N:B: It work only project name then show URL. So it is helpfull for redirect to final page Example: from) /project/page.php to) /project/loginPage.php?id=2 goTo) /project/loginPage.php?id=2 |
|
This is the basic rule to hide index.php from the URL. Put this in your root .htaccess file. mod_rewrite must be enabled with PHP and this will work for the PHP version higher than 5.2.6. RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?/$1 [L] For PHP version less than 5.2.6 try this: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php/$1 [L] You can also use the following code: RewriteEngine On RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /(.*)index.php($| |?) RewriteRule ^ /%1 [R=301,L] |
|
config.php <?php define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PASS", ""); define("DB_NAME", "your_db_name"); ?> Database Calss: <?php Class Database{ public $host = DB_HOST; public $user = DB_USER; public $pass = DB_PASS; public $dbname = DB_NAME; public $link; public $error; public function __construct(){ $this->connectDB(); } private function connectDB(){ $this->link = new mysqli($this->host, $this->user, $this->pass, $this->dbname); if(!$this->link){ $this->error ="Connection fail".$this->link->connect_error; return false; } } // Select or Read data public function select($query){ $result = $this->link->query($query) or die($this->link->error.__LINE__); if($result->num_rows > 0){ return $result; } else { return false; } } // Insert data public function insert($query){ $insert_row = $this->link->query($query) or die($this->link->error.__LINE__); i |
|
Session.php <?php /** *Session Class **/ class Session{ public static function init(){ if (version_compare(phpversion(), '5.4.0', '<')) { if (session_id() == '') { session_start(); } } else { if (session_status() == PHP_SESSION_NONE) { session_start(); } } } public static function set($key, $val){ $_SESSION[$key] = $val; } public static function get($key){ if (isset($_SESSION[$key])) { return $_SESSION[$key]; } else { return false; } } public static function checkSession(){ self::init(); if (self::get("login")== false) { self::destroy(); header("Location:login.php"); } } public static function checkLogin(){ self::init(); if (self::get("login")== true) { header("Location:index.php"); } } public static function destroy(){ session_destroy(); header("Location:login.php"); } } ?> Use for Login Controller: <?php /** * |
|
<?php include '../lib/Session.php'; Session::init(); ?> <?php include '../config/config.php'; ?> <?php include '../lib/Database.php'; ?> <!DOCTYPE html> <head> <meta charset="utf-8"> <title>Login</title> <link rel="stylesheet" type="text/css" href="css/stylelogin.css"/> </head> <body> <div class="container"> <section id="content"> <?php $db = new Database(); if($_SERVER["REQUEST_METHOD"] == "POST"){ $username = mysqli_real_escape_string($db->link, $username); $password = mysqli_real_escape_string($db->link, $password); $query = "SELECT * FROM user WHERE username='$username' and password='$password'"; $result = $db->select($query); if ($result != false) { $value = $result->fetch_assoc(); Session::set("login", true); Session::set("username", $value['username']); Session::set("userId", $value['id']); header("Location: index.php"); //echo "<script>window.location = 'index.php';</scri |
|
{{ ($category->menu_status == 1) ? 'Yes':'No'}} it means if($category->menu_status == 1){ echo "Yes"; }else{ echo "No"; } |
|
Linl: https://gijgo.com/datepicker/example/bootstrap <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap DatePicker</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://unpkg.com/gijgo@1.9.13/js/gijgo.min.js" type="text/javascript"></script> <link href="https://unpkg.com/gijgo@1.9.13/css/gijgo.min.css" rel="stylesheet" type="text/css" /> </head> <body> <input id="datepicker" width="270" /> <script> $('#datepicker').datepicker({ uiLibrary: 'bootstrap' }); </script> </body> </html> |
|
Source : server side rendering https://datatables.net/ head: ----- <link rel="stylesheet" href=" //cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"> body: ----- <table class="table table-bordered"> <thead> <th>Sl</th> <th>Name</th> <th>age</th> <th>Action</th> </thead> <tbody> <tr> <td width="10">1</td> <td>Mr Jhon</td> <td>20</td> <td width="15"> <div class="btn-group"> <a class="btn btn-sm btn-outline-info py-0 " href=" ">View</a> <a class="btn btn-sm btn-outline-danger py-0 " href="">Delete</a> </div> </td> </tr> <tr> <td width="10">1</td> <td>Mr Jhon2</td> <td>19</td> <td width="15"> <div class="btn-group"> <a class="btn btn-sm btn-outline-info py-0 " href=" ">View</a> <a class="btn btn-sm btn-outline-danger py-0 " href="">Delete</a> </div> </td> </tr> </tbody> </table> end body: footer: --------- <script src="//cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script> <script type="text/javascript"> $(document).ready( function () { $('.table').DataTable(); } ); $('.table').DataTable({ "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ] }); </script> stylesheet: ----------- /*Datatable*/ /*header & footer*/ .dataTables_wrapper .dataTables_length, .dataTables_filter, .dataTables_info, .dataTables_paginate { background-color: paleturquoise; } .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_paginate{ float: none; } .dataTables_wrapper .dataTables_length label, .dataTables_wrapper .dataTables_filter label{ padding: 0.175rem 0.5rem; margin-bottom: 0rem; } /*header left + right*/ .dataTables_wrapper .dataTables_length select, .dataTables_wrapper .dataTables_filter input { background-color: #fff; padding: 0px; } /*Table body*/ table.dataTable { margin: 5px 0px; border-collapse: collapse; } .table-bordered, .table-bordered td, .table-bordered th { /*border: 1px solid #dee2e6; border: 1px dashed;*/ } table.dataTable thead th, table.dataTable.no-footer{ border-bottom: unset; } table.dataTable thead th, table.dataTable thead td { padding: 2px 20px; text-transform: capitalize; background-color: turquoise; text-align: center; } table.dataTable tbody td { text-align: center; vertical-align: middle; padding: 2px; } table.dataTable tbody tr { background-color: whitesmoke; } /*Buttom*/ .dataTables_wrapper .dataTables_info { padding: 0.5rem; } .dataTables_wrapper .dataTables_paginate { padding: 0.25em; } .dataTables_wrapper .dataTables_paginate .paginate_button { min-width: 1.5em; padding: 0.2em 0.6em; margin-left: 2px; } <--The end--> |
|
// datatable order by // https://datatables.net/reference/api/order() <script> var table = $('.table').DataTable(); // Sort by column 1 and then re-draw table .order( [ 0, 'desc' ] ) //[ 0, 'asc' ], [ 1, 'asc' ] ist part work properly, .draw(); // 0, 1, 2 colum number </script> |
|
create table student_info( roll int NOT NULL AUTO_INCREMENT, name varchar(30) NOT NULL, gender varchar(30), age int, PRIMARY KEY (roll) ); create table result_info( reg_number int NOT NULL , roll int, gpa double(3,2), group_name varchar(30), gender varchar(30), PRIMARY KEY (reg_number) ); Query for details=>> select student_info.roll, reg_number, name, student_info.gender, group_name, gpa from student_info,result_info where student_info.roll=result_info.roll; |
|
1) $sql="insert into child values(null,'Raiz',15)"; 2) suppose: 4 cloumn (id, name, age, mobile) if u insert all insert into child (name, age, mobile) values ('Raiz',15, 0168060)"; id: auto increment... 3) if insert only name, mobile insert into child (name, mobile) values ('Raiz' 01680607293)"; N:B: Always fill up the 2nd column. After (id) auto increment the 2nd column(name) must be filled. 123222333111 |
|
$search = "companyLogo/companyLogo"; $row = CompanyLogo::where('id', 1)->where('imageSource', 'LIKE', '%'.$search.'%')->first(); if ($row && $row!=null) { unlink($row->imageSource); CompanyLogo::find(1)->update([ 'imageSource'=>"backend/images/companyLogo/logo.jpeg", 'created_at' => Carbon::now() ]); return back()->with('success',' Default logo selected..'); } if($row==null){ return back()->with('success',' Default logo already selected..'); } |
|
<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> RewriteEngine On RewriteCond %{REQUEST_FILENAME} -d [OR] RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^ ^$1 [N] RewriteCond %{REQUEST_URI} (\.\w+$) [NC] RewriteRule ^(.*)$ public/$1 RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ server.php </IfModule> |
|
<!-- Blade file --> <div class="btn-group" role="group" aria-label="Basic example"> <a class="btn" href="{{ url('softDelete', $all_Code->id)}}" onclick="return confirm('Alert message')">Soft-Delete</a> <a class="btn" href="{{ url('forceDelete', $all_Code->id)}}" onclick="return confirm('Alert message')">Fource Delete</a> <a class="btn" href="{{ url('restore', $all_Code->id)}}">Restore</a> <a class="btn" href="{{ url('trashedCode')}}">Trashed Code</a> </div> <!-- web.php --> Route::get('softDelete/{id}', 'CodeController@softDelete')->name('softDelete'); Route::get('forceDelete/{id}', 'CodeController@forceDelete')->name('forceDelete'); Route::get('restore/{id}', 'CodeController@restore')->name('restore'); Route::get('trashedCode', 'CodeController@trashedCode')->name('trashedCode'); <!-- Controller --> public function softDelete($id){ AllCode::find($id)->delete(); return back()->with('danger', 'Code soft delete successfully'); } public function forceDelete($id){ AllCode::onlyTrashed()->find($id)->forceDelete(); return back()->with('forceDelete', 'Code permanently delete successfully'); } public function restore($id){ AllCode::onlyTrashed()->find($id)->restore(); return back()->with('success', 'Code restore successfully'); } public function trashedCode(){ $AllCodes = App\AllCode::onlyTrashed()->get(); foreach($AllCodes as $all_Code){ echo $all_Code->id; } } |
|
Composer composer Update : composer self-update [Ex: 1.0 to 2.0] return old : composer self-update --rollback [Ex: 2.0 to 1.0] Laravel php artisan --version Laravel v{{ Illuminate\Foundation\Application::VERSION }} (PHP v{{ PHP_VERSION }}) php php -v php -version php --version |
|
$LanguageKeys = App\LanguageKey::pluck('id'); $dataList = collect($subtitleKeys)->unique()->pluck('languagekey_id'); |
|
<a class="btn" href="{{url('/edit', [$user->id, $user->age])}}"> Route::get('edit/{id}/{age}', 'Controller@edit')->name('edit'); public function edit(Request $request){ echo $request->id; echo $request->age; } |
|
Blade : <td> @if($social->status == 1) <a href="{{ url('change', [$social->id, $social->status])}}" class="btn">Active</a> @else <a href="{{ url('change', [$social->id, $social->status])}}" class="btn">Inactive</a> @endif </td> web.php : Route::get('/change/{id}/{status}', 'Controller@change')->name('change'); Controller : public function change($id, $status){ $socialId = SocialMedia::find($id); if ($status == 0) { $socialId->status = true; } if ($status == 1) { $socialId->status = false; } $socialId->save(); return back()->with('success','Social media status change'); } N:B: if change have 1 button public function change($id){ if(SocialMedia::find($id)->status==0){ SocialMedia::find($id)->update([ "status" => true ]); }else{ SocialMedia::find($id)->update([ "status" => false ]); } } |
|
ErrorException Trying to get property 'name' of non-object Solve : {{$alluser->admin->name}} {{$alluser->admin['name']}} |
|
catch the relationship error on missing foreign key ------ public function ApproveBy(){ return $this->belongsTo(Admin::class, 'approveBy', 'id')->withDefault(); } ------ {{ $term->ApproveBy['name']}} |
|
blade: <header class="panel-heading panel-heading-gray custom-tab "> <ul class="nav nav-tabs mt-2" id="tabMenu"> <li class="nav-item"> <a href="#firstTab" data-toggle="tab" class="active">1st tab</a> </li> <li class="nav-item"> <a href="#secondTab" data-toggle="tab">2nd tab</a> </li> </ul> </header> <div class="panel-body"> <div class="tab-content"> <div class="tab-pane active" id="adminSocialMedia"> <a href='{{ url('firstTab') }}' target="_blank">Click 1st tab</a> </div> <div class="tab-pane active" id="adminSocialMedia"> <a href='{{ url('secondTab') }}' target="_blank">Click 2nd tab</a> </div> </div> </div> Controller: public function secondTab(){ return back()->with('success', 'This 2nd tab alert') ->withInput(['tab' => 'secondTab']); } Js : <script> //redirect to specific tab $(document).ready(function () { $('#tabMenu a[href="#{{ old('tab') }}"]').tab('show') }); </script> Link: https://medium.com/@grmcameron/redirect-to-a-specific-tab-in-laravel-149398a9e655 |
|
<li class="nav-item start {{ (request()->routeIs('socialMedia*')) ? 'active' : '' }}"> <a href="#" class="nav-link nav-toggle"> <i class="far fa-share-square" aria-hidden="true"></i> <span class="title">Social Media</span> <span class="selected"></span> <span class="arrow open"></span> </a> <ul class="sub-menu"> <li class="nav-item {{ (request()->routeIs('socialMedia.admin*')) ? 'active' : '' }}"> <a href="{{ route('socialMedia.admin') }}" class="nav-link "> <span class="title">Admin</span> </a> </li> <li class="nav-item {{ (request()->routeIs('socialMedia.owner*')) ? 'active' : '' }}"> <a href="{{ route('socialMedia.owner') }}" class="nav-link "> <span class="title">Owner</span> </a> </li> </ul> </li> Route hit [route name] <li class="nav-item {{ (request()->routeIs('socialMedia.admin*')) ? 'active' : '' }}"> <a href="{{ route('socialMedia.admin') }}" class="nav-link"> <span class="title">Admin</span> </a> </li> Route::get('/social-media/admin','Admin\SocialMediaController@admin')->name('socialMedia.admin'); url hit [route url] <a class="btn btn-primary" href='{{ url('social-media/admin') }}'>Admin Social Link</a> Route::get('/social-media/admin','Admin\SocialMediaController@admin')->name('socialMedia.admin'); |
|
Route::get('/clear', function() { Artisan::call('cache:clear'); Artisan::call('config:clear'); Artisan::call('config:cache'); Artisan::call('view:clear'); Artisan::call('route:clear'); return "Cleared!"; }); php artisan optimize |
|
migrate migrate:fresh migrate:install migrate:refresh migrate:reset migrate:rollback migrate:status Rollback[Drop] Last table N:B: Migrate table's "batch" colum's value will be big php artisan migrate:rollback then php artisan migrate [Special] if batch serial no :: 2,2,2,2 if i want rollback last one by primary key php artisan migrate:rollback --step=1 output : 2,2,2 if i want rollback last two by primary key php artisan migrate:rollback --step=2 output : 2 then migrate Warning for below Be careful! This command will drop all data from your DB: Rollback[Drop] all table php artisan migrate:reset Rollback[Drop] & migrate all table php artisan migrate:fresh or php artisan migrate:refresh |
|
https://www.youtube.com/watch?v=OGTG1l7yin4&ab_channel=ImranEmu 1. Firstly Go to Google Maps - https://console.cloud.google.com/ 2. Sign In with your Google account and agree with the terms and conditions 3. Create a project and name it as you want 4. Select the project and click on it 5. Navigate to APIs and Services and click on Libraries 6. Enable the following Libraries one by one 1. Google Javascript API 2. Google Place API 3. Google Direction API 4. Google Geolocation API 5. Google Geocoding API 7. Navigate to APIs and Services and click on Credentials 8. Click on Create Credentials and then the API key and it will show up a screen with API Key 9. Now you can optionally restrict the API key. https://developers.google.com/maps/documentation/javascript/overview#Inline <script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"> </script> if my key abc123 AIzaSyD6V8wBnr9Yb_kcXWFpTsT68okra7TxPCw <script async src="https://maps.googleapis.com/maps/api/js?key=abc123&callback=loadMap"> </script> |
|
<li class="nav-item start {{ (request()->routeIs('socialMedia*')) ? 'active' : '' }}"> <a href="#" class="nav-link nav-toggle"> <i class="far fa-share-square" aria-hidden="true"></i> <span class="title">Social Media</span> <span class="selected"></span> <span class="arrow open"></span> </a> <ul class="sub-menu"> <li class="nav-item {{ (request()->routeIs('socialMedia.admin*')) ? 'active' : '' }}"> <a href="{{ route('socialMedia.admin') }}" class="nav-link "> <span class="title">Admin</span> </a> </li> <li class="nav-item {{ (request()->routeIs('socialMedia.owner*')) ? 'active' : '' }}"> <a href="{{ route('socialMedia.owner') }}" class="nav-link "> <span class="title">Owner</span> </a> </li> </ul> </li> Route hit [route name] <li class="nav-item {{ (request()->routeIs('socialMedia.admin*')) ? 'active' : '' }}"> <a href="{{ route('socialMedia.admin') }}" class="nav-link"> <span class="title">Admin</span> </a> </li> Route::get('/social-media/admin','Admin\SocialMediaController@admin')->name('socialMedia.admin'); url hit [route url] <a class="btn btn-primary" href='{{ url('social-media/admin') }}'>Admin Social Link</a> Route::get('/social-media/admin','Admin\SocialMediaController@admin')->name('socialMedia.admin'); |
|
unique:users,username,id,1 // table, field, idcolumn, value to ignore |
|
<a href="{{ url('owner/mealStatus', [$meal->id, 'breakfast'])}}" Route::get('/mealStatus/{id}/{tab}','Owner\MealController@mealStatus')->name('owner.mealStatus'); public function mealStatus($id, $tab){ $mealId = Meal::find($id); ($mealId->status == true) ? $mealId->status = false : $mealId->status = true; $mealId->save(); return back()->with('success','Meal status change')->withInput(['tab' => $tab]); } |
|
if (Schema::hasTable('users')) { // The "users" table exists... } if (Schema::hasColumn('users', 'email')) { // The "users" table exists and has an "email" column... } |
|
Sql table's[skill] column name : orderBy Controller:: $data['Skill'] = Skill::orderBy('orderBy')->get(); return view('backend.pages.skills', $data); Blade.php @foreach($Skill as $item) <tr> <td width="8%"> <div class="btn-group"> <button type="button" class="btn dropdown-toggle" data-toggle="dropdown"> <i class="far fa-check-circle"></i> {{$item->orderBy}} </button> <div class="dropdown-menu" style="min-width: 4rem; background-color: thistle;"> @for($i=1; $i <= $Skill->count(); $i++) <a href="{{ url('orderBy', ['skills', $item->id, $i, 'tabName'])}}" class="{{$i==$item->orderBy ? 'bg-info disabled pl-2' : 'text-center'}} dropdown-item"> @if($i==$item->orderBy) <i class="far fa-check-circle"></i> @endif {{$i}} </a> @endfor </div> </div> </td> </tr> @endforeach // Web.php Route::get('orderBy/{model}/{id}/{targetId}/{tab}','BackendController@orderBy')->name('orderBy'); // Controller public function orderBy($model, $id, $targetId, $tab){ DB::table($model)->where('id', $id)->update(['orderBy' => $targetId]); return back()->with('success', $model.' orderBy change')->withInput(['tab' => $tab]); } |
|
header("Location: home.php"); header('Location: ' . $_SERVER['HTTP_REFERER']); |
|
Base randomNumber // 79907610 randomFloat // 48.8932 randomLetter // 'b' Lorem word // 'aut' sentence // 'Sit vitae voluptas sint non voluptates.' paragraph // 'Ut ab voluptas sed a nam. Sint autem inventore aut officia aut aut blanditiis.' text //($maxNbChars = 200) // 'Fuga totam reiciendis qui architecto fugiat nemo.' realText //Meaning full sentence... Person // 'Jr.' name($gender = null|'male'|'female') // 'Dr. Zane Stroman' ssn // '123-45-6789' [Social Security Number] Address city // 'West Judge' //A city is a large and permanent settlement //Smaller than a state state // 'NewMexico' //A state is a larger area, which is often governed by its own government. //Larger than a city postcode // '17916' address // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473' country // 'Falkland Islands (Malvinas)' latitude($min = -90, $max = 90) // 77.147489 longitude($min = -180, $max = 180) // 86.211205 PhoneNumber phoneNumber // '201-886-0269 x3767' Company company // 'Bogan-Treutel' jobTitle // 'Cashier' DateTime unixTime($max = 'now') // 58781813 date($format = 'Y-m-d', $max = 'now') // '1979-06-09' time($format = 'H:i:s', $max = 'now') // '20:49:42' amPm($max = 'now') // 'pm' dayOfWeek($max = 'now') // 'Friday' monthName($max = 'now') // 'January' year($max = 'now') // '1993' timezone // 'Europe/Paris' Internet email // 'tkshlerin@collins.com' userName // 'wade55' password // 'k&|X+a45*2[' url // 'http://www.skilesdonnelly.biz/aut-accusantium-ut-architecto-sit-et.html' slug // 'aut-repellat-commodi-vel-itaque-nihil-id-saepe-nostrum' macAddress // '43:85:B7:08:10:CA' Payment creditCardType // 'MasterCard' creditCardNumber // '4485480221084675' bankAccountNumber // "SA0218IBYZVZJSEC8536V4XC" creditCardExpirationDateString // '04/13' iban($countryCode) // 'IT31A8497112740YZ575DJ28BP4' swiftBicNumber // 'RZTIAT22263' Color hexcolor // '#fa3cc2' rgbcolor // '0,255,122' rgbCssColor // 'rgb(0,255,122)' safeColorName // 'yellow' colorName // 'SkyBlue' File fileExtension // 'avi/jap/png' Image imageUrl($width = 640, $height = 480) // 'http://lorempixel.com/640/480/' image($dir = '/tmp', $width = 640, $height = 480) // '/tmp/13b73edae8443990be1aa8f1a483bc27.jpg' uuid // '7e57d004-2b97-0e7a-b45f-5387367791cd' [Universally unique identifier] Barcode ean13 // '4006381333931' //International Article Number(ean) ean8 // '73513537' isbn13 // '9790404436093' //International Standard Book Number(isbn) isbn10 // '4881416324' Miscellaneous boolean // false/true md5 // 'de99a620c50f2990e87144735cd357e7' sha1 // 'f08e7f04ca1a413807ebc47551a40a20a0b4de5c' sha256 // '0061e4c60dac5c1d82db0135a42e00c89ae3a333e7c26485321f24348c7e98a5' locale // en_UK countryCode // UK languageCode // en currencyCode // EUR emoji // 😁 HtmlLorem randomHtml // <html><head><title><table>any code</table></body></html> -------------- total : 63 |
|
composer create-project laravel/laravel name composer require laravel/ui php artisan ui vue --auth npm install && npm run dev laravel 6 composer create-project --prefer-dist laravel/laravel blog "6.*" composer require laravel/ui "^1.0" --dev php artisan ui vue --auth npm install && npm run dev |
|
Database : ---------- CREATE TABLE `refresh_status` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `time` bigint(20) NOT NULL DEFAULT '5' COMMENT 'Second', `status` tinyint(4) NOT NULL COMMENT '0=hide, 1=show', PRIMARY KEY (`id`) ); INSERT INTO `refresh_status` (`id`, `time`, `status`) VALUES (1, 5, 1); ============== head.blade.php -------------- <head> @php $time = DB::table('refresh_status')->where('status', true)->first(); @endphp <meta http-equiv="refresh" content="{{ ($time==true)? $time->time:''}}"> </head> ---------------- header.blade.php ---------------- <ul class="navbar-nav m-auto"> <li class="nav-item pl-2" style="margin-top: -6.5px;"> <small class="title">Refresh Status</small> @php $status = DB::table('refresh_status')->first(); @endphp <!-- 1st style --> <a style="line-height: 18px; display: block;" href="{{ url('refreshStatus', 'status') }}" class="btn btn-sm py-0 {{($status->status==true) ? 'btn-success':'btn-danger'}}" title="Click for {{($status->status==true) ? 'Off':'On'}}">{{($status->status==true) ? 'On':'Off'}} </a> <!-- 2nd style --> <div style="display: flex;" class="btn-group"> <a class="p-0 btn btn-sm btn-danger" href="{{ url('refreshStatus', 'decrease') }}" title="Click for {{($status->status==true) ? 'decrease[-]':''}}" {{($status->status==true) ? '':'hidden'}} {{($status->time==0) ? 'hidden':''}} {{$status->time}}>−</a> <a class="p-0 btn btn-sm {{($status->status==true) ? 'btn-secondary':'btn-danger'}}" href="{{ url('refreshStatus', 'status') }}" title="Click for {{($status->status==true) ? 'Off':'On'}}" style="line-height: {{($status->status==true) ? 'normal':'18px'}};">{{($status->status==true) ? 'On ['.$status->time.'”]':'Off'}}</a> <a class="p-0 btn btn-sm btn-success" href="{{ url('refreshStatus', 'increase') }}" title="Click for {{($status->status==true) ? 'increase[+]':''}}" {{($status->status==true) ? '':'hidden'}}>+</a> </div> </li> </ul> ======= web.php ------- // Page refresh status Route::get('/refreshStatus/{value}', 'HomeController@refreshStatus')->name('refreshStatus'); ================== HomeController.php ------------------ use DB; class HomeController extends Controller { public function refreshStatus($value){ $dbInfo = DB::table('refresh_status')->first(); if ($value=='status'){ $refreshStatus = $dbInfo->status; ($refreshStatus==1) ? $changeValue=false : $changeValue=true; $field = 'status'; }elseif($value=='decrease' || $value=='increase'){ $time = $dbInfo->time; ($value=='decrease') ? $changeValue=$time-1 : $changeValue=$time+1; $field = 'time'; } DB::table('refresh_status')->update([$field => $changeValue]); return back(); } } <-------The End--------> |
|
php artisan make:seeder UserSeeder --- UserSeeder: public function run(){ DB::table('user')->insert([ 'name' => 'Aslam', 'email' => 'aslam@email.com', 'email_verified_at' => now(), 'password' => '12345678', // password 'remember_token' => '123321', ]); } } --- DatabaseSeeder: public function run(){ $this->call([ UserSeeder::class, AdminSeeder::class, ClientSeeder::class, ]); } php artisan db:seed or php artisan migrate:refresh --seed If use laravel faker UserSeeder: use Faker\Factory as Faker; public function run(){ $faker = Faker::create(); foreach (range(1, 5) as $value) { DB::table('users')->insert([ 'name' => $faker->name, 'email' => $faker->email, 'email_verified_at' => now(), 'password' => Hash::make('123456'), // password 'remember_token' => '123321', ]); NB: also use another DB; } } } |
|
$arr = array('January', 'February', 'July', 'August', 'March', 'April', 'May', 'June', 'September', 'October', 'November', 'December'); $arr2 = $arr; $loop=1; foreach ($arr as $k => $currVal) { unset($arr2[$k]); foreach ($arr2 as $k => $v) { $nextVal = $v; break; } echo $loop.") "."Current=>".$currVal; echo "<-->"; echo "Next=>".$nextVal."<br>"; $loop++; } Link: https://stackoverflow.com/questions/4148501/get-previous-array-values-in-foreach |
|
Blade.php ========= <?php $array = array('country','city', 'area'); ?> @foreach($array as $key => $country) <form action="{{url($country)}}" method="post"> @csrf <button type="submit" class="mt-2 btn btn-success">{{$country}}</button> </form> @endforeach web.php ======= $pages = ltrim(\Request::getRequestUri(), '/'); Route::post($pages, [CountryController::class, 'itrerate'])->name($pages); CountryController.php ===================== public function itrerate(Request $request){ echo $request->route()->uri; echo 'Anything'; } |
|
1) One-dimensional array ======================== Input ----- $array = array('country', 'city', 'area'); or $array = ['country', 'city', 'area']; Output ------ @foreach($array as $k => $country) {{$country}} @endforeach // Smart way to call array Controller.php ============== $data['trees'] = Tree::all(); Blade.php ========= //array_column() expects at least 2 parameters $array = array_column($trees->toArray(), 'name_column'); @foreach($array as $k => $country) {{$country}} @endforeach ********************************************* 2) Two-dimensional array ======================== Input ----- @php $teams = [ [ 'name' => 'Abc', 'age' => 12 ], [ 'name' => 'Abc2', 'age' => 15 ] ]; @endphp Output ------ @foreach ($teams as $team) {{$team['name']}} {{$team['age']}} @endforeach array:3 [▼ "base" => "EUR" "date" => "2023-01-19" "rates" => array:168 [▼ "AED" => 4.147043 "AFN" => 118.466773 "ALL" => 120.73174 ]; or $lists = [ [1, 'private', 'withdraw', '0.003'], [2, 'private', 'deposit', '0.0003'], [3, 'business', 'withdraw', '0.005'], [4, 'business', 'deposit', '0.0003'] ]; foreach($lists as $list){ foreach($list as $value){ echo $value; } } ========== $currencyAPI = 'https://developers.paysera.com/tasks/api/currency-exchange-rates'; $data['todayCurrency'] = json_decode(file_get_contents($currencyAPI), true); @foreach($todayCurrency['rates'] as $name => $value) <tr> <td>{{ $name }}</td> <td>{{ $value }}</td> </tr> @endforeach ********************************************* 3) Three-dimensional array ========================== Input ----- @php $teams = [ 'management_team' => [ 'name' => 'Management Team', 'data' => [ [ 'name' => 'Abc', 'age' => 15 ], [ 'name' => 'Abc2', 'age' => 18 ] ] ] ]; @endphp output ------ {{$teams['management_team']['name']}} @foreach ($teams['management_team']['data'] as $team) {{$team['name']}} {{$team['designation']}} @endforeach ********************************************* 4) Three-dimensional array(Multiple) =================================== Input ----- @php $teams = [ 'management_team' => [ 'name' => 'Management Team', 'data' => [ [ 'name' => 'Abc', 'age' => 18 ], [ 'name' => 'Abc2', 'age' => 20 ] ] ], 'management_team2' => [ 'name' => 'Management Team2', 'data' => [ [ 'name2' => 'Abc', 'age2' => 18 ], [ 'name2' => 'Abc2', 'age2' => 20 ] ] ] ]; @endphp output ------ @foreach ($teams as $key => $team) {{$team['name']}} @foreach ($team['data'] as $info) {{$info['name']}} {{$info['designation']}} @endforeach @endforeach === The end === |
|
1) Default: web.php Auth::routes(); Route::fallback(function () { return abort(404); }); 2) If u want register not working web.php //Auth::routes(); Auth::routes(['register' => false]); Route::fallback(function () { return abort(404); }); 3) Coustom 404 make Route::fallback(function () { return view('404'); }); views/404.blade.php /* <!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>404 : Error Page</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> </head> <body> <div class="container mt-5 pt-5"> <div class="alert alert-danger text-center"> <h2 class="display-3">404</h2> <p class="display-5">Oops! Something is wrong.</p> <a href="https://aslambd.com" class="btn btn-primary">Return homepage</a> </div> </div> </body> </html> */ |
|
// App\Http\Controllers\Redirect; use Redirect; $validator = Validator::make($request->all(),[ 'iconName'=> 'required|unique:code_type_icons,iconName', 'iconLink'=> 'required|unique:code_type_icons,iconLink' ]); if($validator->fails()) { $messages = $validator->messages();// get the error message. return Redirect::back()->withErrors($validator); } 1st... @if($errors) @foreach ($errors->all() as $error) <div class="alert alert-danger text-center alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $error }}</strong> </div> @endforeach @endif 2nd... return back()->with('success', 'Code type add successfully'); @foreach (['success', 'danger', 'warning', 'info'] as $alert) @if ($message = Session::get($alert)) <div class="alert alert-{{$alert}} text-center alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $message }}</strong> </div> @endif @endforeach <script type="text/javascript"> window.setTimeout(function() { $(".alert").fadeTo(500, 0).slideUp(500, function(){ $(this).remove(); }); }, 5000); </script> another way... return back()->with('success', 'Code type icon add successfully'); return back()->with('danger', 'Code type icon add successfully'); return back()->with('info', 'Code type icon add successfully'); @foreach (['success', 'danger', 'warning', 'info'] as $alert) @if ($message = Session::get($alert)) <div class="alert alert-{{$alert}} text-center alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $message }}</strong> </div> @endif @endforeach <script type="text/javascript"> window.setTimeout(function() { $(".alert").fadeTo(500, 0).slideUp(500, function(){ $(this).remove(); }); }, 5000); </script> <style type="text/css"> .alert { margin-top: 0px; position: absolute; right: 0px; z-index: 1; color: white; } .close { color: #000 !important; margin: 0 -8px 0px 10px; line-height: 20px; } ul li { list-style: none; margin-top: 20px; } .close:hover { color: black; } </style> |
|
@php $languageId = session()->get('languageId'); $id=$languageId; switch ($languageId) { case $id: $Language = App\Language::find($id); echo $Language->name; break; default: echo "321"; } @endphp |
|
in db migration batch id inclise [1->2] php artisan migrate:rollback php artisan migrate |
|
$uniqueNumberFound = false; while (!$uniqueNumberFound){ $employee_id=rand(1, 5); $sql3="SELECT * FROM employee where employee_id='$employee_id'"; $rowcount=mysqli_query($hrm, $sql3); $num= mysqli_num_rows($rowcount); if ($num==0){ $uniqueNumberFound = true; } } echo $employee_id; ?> |
|
$validated = $request->validate([ 'codeType' => 'required|unique:code_types,codeType,userId'.\Auth::user()->id, ]); or $id = $request->id; $validator = Validator::make($request->all(),[ 'field'=>"required|unique:table,colum,$id" ]); |
|
Add new column public function new(){ $table = 'members'; $column = 'abc'; DB::select("ALTER TABLE $table ADD $column VARCHAR(255)"); DB::statement("ALTER TABLE $table ADD $column VARCHAR(255)"); return view('admin.member.registration'); } link::https://blog.quickadminpanel.com/5-ways-to-use-raw-database-queries-in-laravel/ |
|
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Notice extends Model{ use SoftDeletes; protected $guarded = []; } |
|
1st: php artisan make:seeder SqlFileSeeder ---------- 2nd: put the sql file here database\test.sql ---------- 3rd: database\seeds\SqlFileSeeder.php; <?php use Illuminate\Database\Seeder; class SqlFileSeeder extends Seeder { public function run(){ $path = 'database\test.sql'; $sql = file_get_contents($path); DB::unprepared($sql); } } ---------- 4th: database\seeds\DatabaseSeeder.php <?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { public function run() { $this->call(SqlFileSeeder::class); } } ---------- 3rd + 4th: Shortcuts way database\seeds\DatabaseSeeder.php use DB; class DatabaseSeeder extends Seeder { public function run(){ $path = 'database\test.sql'; $sql = file_get_contents($path); DB::unprepared($sql); } } ---------- 5th: php artisan db:seed php artisan db:seed --class=SqlFileSeeder ---------- 6th: Delete full db's table from phpmysql php artisan db:wipe ========== Link:: https://www.nicesnippets.com/blog/how-to-run-sql-file-or-query-in-laravel-seeder |
|
'min'=>"required|numeric", 'max'=>"required|numeric|gt:min", lt lessthan gt gatherthan gte gatherthan equal https://github.com/laravel/framework/issues/24650 |
|
name="user_type[]" $user_type = $request->input('user_type'); $array = []; $serial = 0; foreach ($user_type as $field) { $array[$serial] = $field; $serial = $serial + 1; } $field = "(".implode(', ', $array).")"; |
|
$path="images/general/"; $default="default.jpg"; if ($request->hasFile('photo')){ if($files=$request->file('photo')){ $photo = $request->photo; $fullName=time().".".$photo->getClientOriginalExtension(); $files->move(public_path($path), $fullName); $photoLink = $path . $fullName; } }else{ $photoLink = $path . $default; } https://www.codegrepper.com/code-examples/php/laravel+upload+image+to+public+folder |
|
html ==== <div class="form-group col-4"> <select class="multiple-checkboxes" multiple="multiple" name="user_type[]"> @foreach($userTypes as $user) <option value="{{$user->name}}">{{$user->name}}</option> @endforeach </select> </div> Controller ========== $user_type = $request->input('user_type'); if ($user_type){ $array = []; $serial = 0; foreach ($user_type as $field) { $array[$serial] = $field; $serial = $serial + 1; } $user_type = implode(', ', $array); } output ====== user, user2, user3... |
|
composer dump-autoload composer install php artisan cache:clear php artisan clear-compiled <-- OR --> Deleted the file "/public_html/bootstrap/cache/config.php" then I ran "php artisan config:cache" |
|
return Redirect::to('Blade page name'); With data return Redirect::route('settings')->with(['data' => $data])->withInput(['tab' => $tab]); |
|
insert() [Does not insert (created_at, updated_at)] create() [Insert (created_at, updated_at)] ---------------------------- $user = User::insertGetId([ 'name' => $request->name [Does not insert (created_at, updated_at)] ]); Answer: $user = 2; -------------------- $user = User::create([ 'name' => $request->name [Insert (created_at, updated_at)] ]); Answer: $user->id = 2; ------------------------- N:B: createGetId [Not working] |
|
Capital : A-Z, small : a-z @foreach(range('a','z') as $letter) {{$letter}} @endforeach Answer: a, b, c, d ------------------ @foreach($users as $user) {{ chr(64+ $loop->iteration) }}) {{$user->name}} @endforeach Answer: A) user, B)User2 ------------------------ @foreach($users as $user) {{ chr(96+ $loop->iteration) }}) {{$user->name}} @endforeach Answer: a) user, b)User2 ------------------------ https://laracasts.com/discuss/channels/site-improvements/loop-iteration-as-a-in-blade |
|
$questionList = QuestionList::with('getOption')->pluck('id'); $answerList = AnswerList::where('userId', $user)->pluck('questionId'); $unVoteQuestion = $questionList->diff($answerList); $data['addVote'] = QuestionList::with('getOption')->whereIn('id', $unVoteQuestion)->get(); return view('home', $data); |
|
https://blog.quickadminpanel.com/how-to-import-csv-in-laravel-and-choose-matching-fields/ https://www.itsolutionstuff.com/post/laravel-create-csv-file-from-custom-array-using-maatwebsiteexample.html https://makitweb.com/export-data-to-csv-excel-format-in-laravel-8/ |
|
<!-- All Column --> <?php if(isset($_SESSION['tableName'])){ ?> <div class="tab-pane" id="column"> <p class="bg-success text-center mb-2"><?= $_SESSION['tableName']; ?>'s [columns]</p> <?php // $tableName = $_SESSION['tableName']; $column = "SHOW columns FROM $tableName"; $columnResult = mysqli_query($conn, $column); $TotalColumn = mysqli_num_rows($columnResult); $col_4 = 1; $loop = 1; $headFirst = 1; ?> <form action="action.php" method="POST"> <div class="row"> <?php while($row = mysqli_fetch_array($columnResult)){ ?> <?php if($col_4=='1'){ ?> <table id="example1" class="table table-bordered table-striped col-4 mb-0"> <?php if($headFirst=='1'){?> <thead> <tr class="text-center"> <th class="bg-secondary">No</th> <th>Column name</th> <th>Action</th> </tr> </thead> <?php } ?> <tbody> <tr> <td width="20%" class="bg-secondary text-center"><?= $loop; ?></td> <td width="auto"><?= $row['Field']; ?></td> <?php if($row['Field']!='id') {?> <td width="20%" class="text-center"><a class="btn btn-sm btn-danger" href="action.php?columnName=<?=$row['Field']; ?>&tab=column">Delete</a></td> <?php }else{ ?> <td width="20%" class="bg-warning text-center p-0"> Primary key can't delete </td> <?php } ?> <tr> </tbody> </table> <?php }elseif($col_4=='2'){ ?> <table id="example1" class="table table-bordered table-striped col-4 mb-0"> <?php if($headFirst=='2'){?> <thead> <tr class="text-center"> <th class="bg-secondary">No</th> <th>Column name</th> <th>Action</th> </tr> </thead> <?php } ?> <tbody> <tr> <td width="20%" class="bg-secondary text-center"><?= $loop; ?></td> <td width="auto"><?= $row['Field']; ?></td> <?php if($row['Field']!='id') {?> <td width="25%" class="text-center"><a class="btn btn-sm btn-danger" href="action.php?columnName=<?=$row['Field']; ?>&tab=column">Delete</a></td> <?php }else{ ?> <td width="25%" class="bg-warning text-center p-0"> Primary key can't delete </td> <?php } ?> <tr> </tbody> </table> <?php }else{ ?> <table id="example1" class="table table-bordered table-striped col-4 mb-0"> <?php if($headFirst=='3'){?> <thead> <tr class="text-center"> <th class="bg-secondary">No</th> <th>Column name</th> <th>Action</th> </tr> </thead> <?php } ?> <tbody> <tr> <td width="20%" class="bg-secondary text-center"><?= $loop; ?></td> <td width="auto"><?= $row['Field']; ?></td> <?php if($row['Field']!='id') {?> <td width="20%" class="text-center"><a class="btn btn-sm btn-danger" href="action.php?columnName=<?=$row['Field']; ?>&tab=column">Delete</a></td> <?php }else{ ?> <td width="20%" class="bg-warning text-center p-0"> Primary key can't delete </td> <?php } ?> <tr> </tbody> </table> <?php } ?> <?php (($col_4=='1'||'2') ? $col_4++ : $col_4='1' ); $loop++; $headFirst++; } ?> </div> </form> </div> <?php } ?> |
|
<td> <a href="{{asset('')}}/{{$report->file}}" class="btn btn-large pull-right" target="_blank" download=""> <i class="fas fa-download pr-2"></i>Download </a> </td> |
|
Controller $data['patients'] = Appointment::where('doctor_id', Auth::id())->get()->groupBy('patient_id'); Blade @foreach($patients as $patient2) @foreach($patient2->take(1) as $patient) {!!$patient->date!!} @endforeach @endforeach |
|
Rooms [id, room_no] -> Ex:1, 2, 3, 4, 5; CabinBooking [id, check_in, check_out, room_no] -> 2, 5 UnBook: 1, 3, 4 // All rooms $rooms = Room::where('room_type', 'cabin')->orderBy('room_no', 'Asc')->pluck('room_no'); *********** // Booked $booked = CabinBooking::where([ ['cabin_bookings.check_in', '<=', $check_in], ['cabin_bookings.check_out', '>=', $check_out] ]) ->orwhere([ ['cabin_bookings.check_in', '>=', $check_in], ['cabin_bookings.check_out', '<=', $check_out] ])->pluck('room_no'); ----------- // Or $booked = CabinBooking::where([ ['cabin_bookings.check_in', '<=', $check_in], ['cabin_bookings.check_out', '>=', $check_in] ]) ->orwhere([ ['cabin_bookings.check_in', '>=', $check_out], ['cabin_bookings.check_out', '<=', $check_out] ])->pluck('room_no'); ----------- // Or $booked = CabinBooking::whereBetween('cabin_bookings.check_in', [$check_in, $check_out]) ->orWhereBetween('cabin_bookings.check_out', [$check_in, $check_out]) ->orWhere(function ($query) use ($check_in, $check_out) { $query->where('cabin_bookings.check_in', '<', $check_in) ->where('cabin_bookings.check_out', '>', $check_out); })->pluck('room_no'); *********** // UnBook filter $data['unBook'] = $rooms->diff($booked); |
|
@if (count($posts)) @if($query->isEmpty()) |
|
@php $hours_start = strtotime('08:00:00'); $hours_end = strtotime('18:00:00'); $hours = $hours_end - $hours_start; //amount of hours working in day $hours = $hours / 1800; // 30 munite slot for($i = 0; $i <= $hours; $i++){ // double hours for 30 minute increments $minutes_to_add = 1800 * $i; // add 30 - 60 - 90 etc. $timeslot = date('h:i:s', strtotime($hours_start)+$minutes_to_add); date('h:i a', strtotime($timeslot)). "<br>"; } @endphp 06:00 am 06:30 am 07:00 am 07:30 am 08:00 am |
|
mktime(hour, minute, second, month, day, year, is_dst); <?php $iTimestamp = mktime(1,0,0,1,1,date('Y')); for ($i = 0; $i < 48; $i++) { echo 1+$i.") ". date('h:i a', $iTimestamp) . "\n<br />"; $iTimestamp += 1800; } ?> ====================== $hour = -1; while($hour++ < 23) { $timetoprint = date('h:i a',mktime($hour,0,0,1,1,2011)); echo 1+$hour.")" .$timetoprint . "<br>"; } {{-- # 24 hrs H:i // output 14:20 # 12 hrs h:i // output 2:20 --}} |
|
$validator = Validator::make($request->all(),[ 'check_in'=>'required|date|before_or_equal:check_out', 'check_out'=>'required|date|after_or_equal:check_in', ]); return [ 'pay_period_start'=>'date', 'pay_period_end' => 'date', 'work_date' => 'date|after_or_equal:pay_period_start|before_or_equal:pay_period_end', ]; |
|
https://stackoverflow.com/questions/54775177/select-where-all-3-columns-are-not-null-at-the-same-time-laravel-query-builder |
|
1) Html ======= <form action="{{ route('appointment.add') }}" method="post" enctype="multipart/form-data"> @csrf <input type="hidden" name="user_id" value="{{ $doctorId = $doctor->user_id }}"> <input type="text" class="select-date datepicker" name="date" id="date" placeholder="Day-Month-Year"/> <select class="select-time" name="time" id="time"> <option value="">Select time</option> </select> <button type="submit">Add now</button> </form> 2) Js action ========= <script> $(document).ready(function() { $('.select-date').change(function() { var date = $(this).val(); var doctorId = '{{ $doctorId }}'; $('.select-time').html(''); $.ajax({ url: "{{ route('search.date') }}", method: "get", data: { date: date, doctorId: doctorId }, success: function(result) { $('.select-time').append('<option selected>Select time</option>'); $.each(result, function(key, value) { $('.select-time').append('<option disabled2 value="' + value + '">' + value + '</option>'); }); } }) }); }); </script> 3) web.php ========== Route::get('search-date', 'PatientController@search_date')->name('search.date'); 4) PatientController ==================== public function search_date(Request $request) { $allTime = array('8:10 AM', '8:15 AM', '8:20 AM', '8:25 AM', '8:30 AM'); $booked = Appointment::where('doctor_id', $request->doctorId) ->where('date', date('Y-m-d', strtotime($request->date))) ->pluck('time')->toArray(); $unBook = array_diff($allTime, $booked); return response()->json($unBook); } 5) web.php ========== Route::post('appointment-add', 'PatientController@appointment_add')->name('appointment.add'); 6) PatientController ================= public function appointment_add(Request $request){ Appointment::Create([ 'appointment_id' => uniqid(), 'patient_id' => Auth::id(), 'doctor_id' => $request->user_id, 'date' => date('Y-m-d', strtotime($request->date)), 'time' => $request->time ]); return back()->with('success', 'Appointment add successfully'); } database table ============== Schema::create('appointments', function (Blueprint $table) { $table->id(); $table->string('appointment_id')->nullable(); $table->integer('patient_id'); $table->integer('doctor_id'); $table->date('date')->nullable(); $table->string('time')->nullable(); }); |
|
https://stackoverflow.com/questions/32387575/how-to-properly-merge-multiple-collections-in-laravel $paid = Payment::pluck('id')->toArray(); $newCompete = array(2=>'Others'); $paid2 = collect($paid)->concat($newCompete)->toArray(); |
|
https://youtu.be/_xOAdCprXY0 |
|
https://www.youtube.com/watch?v=iaj4rQ8UH24&t=1010s&ab_channel=JustSteveKing |
|
<style> input{width: 100%; text-align: center;} input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { display: none; } </style> <tbody style="font-weight: bold;"> <tr> <td colspan="5">Subtotal:</td> <td id="sb_total"></td> </tr> <tr> <td colspan="5">Discount:</td> <td width="10"> <input type="number" min="0" id="a_discount" value="0"> </td> </tr> <tr> <td colspan="5">Less Amount:</td> <td> <input type="number" min="0" id="b_less" value="0"> </td> </tr> <tr> <td colspan="5">Vat:</td> <td> <input type="number" min="0" id="c_vat" value="0"> </td> </tr> <tr> <td colspan="5">Total:</td> <td id="t_amount"></td> </tr> </tbody> <script> $('#sb_total, #a_discount, #b_less, #c_vat').blur(function(){ var list_total = $('#subtotal').val(); var vat_amount = 0; var less_amount = 0; // $('#a_discount').each(function(){ var discount = $('#a_discount').val(); var discount_type = $('#a_discount').attr('data'); if(!(discount)){ discount = 0; }if(!(discount_type)){ discount_type = 0; } var discount_amount = (list_total*(discount/100)); if(discount_type == '1'){ discount_amount = discount; } // Less var less_amount = $('#b_less').val(); if(!(less_amount)){ less_amount = 0; } // vat var vat = $('#c_vat').val(); if(!(vat)){ vat = 0; } var vat_amount = (list_total*(vat/100)); // }); var total_amount = (parseInt(list_total)+parseInt(vat_amount))-(parseInt(discount_amount)+parseInt(less_amount)); $('#t_amount').html(total_amount.toFixed(2)); $('#t_amount').append('<input type="hidden" name="t_amount" value="'+total_amount+'"/>'); }) // $('#t_amount').text(discount.toFixed(2)); </script> function load_cart(){ $.ajax({ url:"includes/cart_process.php", method:"GET", dataType:"json", success:function(data) { $('#cart_details').html(data.cart_details); $('#sb_total').text(data.sub_total); $('#total').html(data.total); $(".mem_details").html(data.member.member_details); $("#m_info").html(data.member.member_info); calculation(); } }); } |
|
<?php $sql = "SELECT * FROM users"; $result = mysqli_query($con, $sql); // if single output $result->fetch_assoc()['name']; // Loop data foreach($result as $row): echo $row["name"]; endforeach; ?> |
|
$sql2 = "SELECT count(id) as id, sum(total_rcv) as total FROM sd_order_more WHERE (mobile= '$mobile' && customerID = 0) and activity = 1"; $result2 = mysqli_query($mysqli, $sql2); $result3 = mysqli_query($mysqli, $sql2); $service_number = $result2->fetch_assoc()['id']; $total_expense = $result3->fetch_assoc()['total']; |
|
λ mysql -u root -p show databases; use databaseName; source sqlPath; // also File drag and drop allow. |
|
$_SESSION['postTimer'] = (time()+(24*60*60))*1000; <?php if(isset($_SESSION['postTimer']) && (time()*1000 < $_SESSION['postTimer'])){ ?> <script> // Set the date we're counting down to var countDownDate = <?= $_SESSION['postTimer']; ?>; var x = setInterval(function() { var now = new Date().getTime(); var distance = countDownDate - now; // var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); document.getElementById("timeCount").innerHTML = hours + "h " + minutes + "m " + seconds + "s "; if (distance < 0) { clearInterval(x); document.getElementById("submitButton").disabled = false; document.getElementById("timeCount").style.display = "none"; }else{ document.getElementById("submitButton").disabled = true; } }, 1000); </script> <?php }else{ unset($_SESSION['postTimer']); } ?> |
|
$faker = Faker\Factory::create(); foreach (range(1, 10) as $value) { DB::table('subjects')->insert([ 'name' => $faker->name ]); } |
|
https://www.itsolutionstuff.com/post/laravel-eloquent-exists-and-doesntexist-exampleexample.html |
|
https://spatie.be/docs/laravel-pdf/v1/introduction spatie::pdf package requires PHP 8.2+, Laravel 10+. All see another four(4) pdf generator https://spatie.be/docs/laravel-pdf/v1/alternatives 1) laravel-dompdf 2) wkhtmltopdf 3) mPDF 4) FPDF |
|
$input = $request->except('_token', 'image_path'); |
|
https://stackoverflow.com/questions/23411520/how-to-fix-error-laravel-log-could-not-be-opened |
|
@php $colors = array('bg-info', 'bg-secondary', 'bg-dark', 'bg-primary', 'bg-white', 'bg-success', 'bg-warning', 'bg-secondary', 'bg-danger', 'bg-dark'); @endphp |
|
MAIL_MAILER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=587 MAIL_USERNAME=abc@gmail.com MAIL_PASSWORD=abc MAIL_FROM_ADDRESS=abc@gmail.com MAIL_FROM_NAME=Name MAIL_ENCRYPTION=tls |
|
if($_POST["action"] == "add" && $_POST["type"] == "service"){ if(!empty($_SESSION["shopping_cart"])){ $itemList = array(); foreach($_SESSION["shopping_cart"] as $keys => $values) { $itemList[] = array('itm_id'=>$values["itm_id"], 'qty_id'=>$values["qty_id"]); } $key = array_search($_POST["itm_id"], array_column($itemList, 'itm_id')); if ($key !== false) { $qty_id = $itemList[$key]['qty_id']; // this line add quantity... $_SESSION["shopping_cart"][$key]['qty_id'] = $qty_id+1; }else{ $item_array = array('itm_id'=>$_POST["itm_id"], 'qty_id'=>1, 'type'=>$_POST["type"]); $_SESSION["shopping_cart"][] = $item_array; } }else{ $item_array = array('itm_id'=>$_POST["itm_id"], 'qty_id'=>1, 'type'=>$_POST["type"]); $_SESSION["shopping_cart"][] = $item_array; } } |
|
if ($stmt_m1->num_rows == 0) { $orderID = 'INV-0000001'; }else{ if ($stmt_m = $mysqli->prepare("SELECT id, CONCAT( '" . $prefix . "-', LPAD(id + 1,7,'0') ) FROM sd_order_more ORDER BY id DESC")) { $stmt_m->execute(); $stmt_m->store_result(); $stmt_m->bind_result($prefx_id, $orderID); $stmt_m->fetch(); $stmt_m->close(); } } |
|
<?php session_start(); require_once("db_connect.php"); $p_cart = array(); $c_cart = array(); foreach($_SESSION["shopping_cart"] as $keys => $values){ if($values["type"] == "product"){ $p_cart[] = array('itm_id'=>$values['itm_id'], 'qty_id'=>$values["qty_id"]); } } foreach($_SESSION["combo_cart"] as $keys => $values){ $c_cart[] = $values['combo_id']; } $product = json_encode($p_cart); $combo = json_encode($c_cart); if(isset($_POST["action"])){ $cartName = $_POST["cartName"]; $sql = "INSERT INTO cart_hold VALUES(null, '$cartName', '$product', '$combo')"; $result = mysqli_query($mysqli, $sql); } unset($_SESSION["shopping_cart"]); unset($_SESSION["combo_cart"]); $data = array( 'cart' => $cartName ); echo json_encode($data); ?> |
|
$payment_mtd = 'bKash'; $paid = 20; $bkash = 10; $lists = ['bkash', 'cash']; foreach($lists as $name){ if($name == $payment_mtd){ $$name = $paid; or ${$name} = $paid; } } echo bkash; print : 20; https://wholesomecode.net/dynamic-variable-names-in-php/ |
|
https://www.geeksforgeeks.org/how-to-bind-an-array-to-an-in-condition-in-php/ <?php $category = ['salary', 'bonus', 'other']; $type2 = implode('\', \'', $category); $sql = "SELECT * FROM sd_expns_c WHERE type2 IN ('$type2') && activity = 1 ORDER BY id ASC"; $result = mysqli_query($mysqli, $sql); while ($row = $result->fetch_assoc()) { ?> <option value="<?= $row['id']; ?>"><?= $row['menu_name']; ?></option> <?php } ?> |
|
$test_variable = 'value1'; // 1st way if ($test_variable === 'value1' || $test_variable === 'value2' || $test_variable === 'value3' || $test_variable === 'value4') { // code } // 2nd way if (in_array($test_variable, ['value1', 'value2', 'value3', 'value4'])) { // code } // 3rd way $test_array = ['value1', 'value2', 'value3', 'value4']; if (in_array($test_variable, $test_array)) { // code } https://inthedigital.co.uk/use-phps-in_array-to-compare-a-variable-to-multiple-values/#:~:text=August%2028th%2C%202020-,Use%20PHP's%20in_array()%20to%20compare%20a%20variable%20to%20multiple,instead%20of%20complex%20if%20expressions. |
|
echo date('y-n-j', strtotime('2024-09-03')); result: 24-9-3 |
|
$fillable => serves as a "white list" of attributes that should be fillable. $guarded => serves as a "black list" of attributes that should not fillable. $fillable is opposite $guarded Example 1 protected $fillable = ['name', 'email']; It means we want to insert only name, email colmn values Example 2 protected $guarded = ['name', 'email']; It means we want to ignore(block) only name, email. That means we don't want to insert name, email colmn value Example 3 protected $guarded = []; We want to insert all columns values If we want to ignore all the fields, we can use: protected $guarded = ['*']; If we want to insert all fields, we can use: protected $guarded = []; |
|
[data.json => code, message column) $link = file_get_contents(public_path('data.json')); $dataArray = json_decode($link, true); $errorList = array(); foreach ($errors as $error){ $result = array_filter($dataArray, function($item) use ($error) { return $item['code'] === $error; }); $result = array_values($result); // return dd($result[0]['message']); $errorList[] = $error .': '. $result[0]['message']; } |
|
https://www.luckymedia.dev/blog/google-drive-api-setup-for-laravel-10-integration-part-1 https://www.luckymedia.dev/blog/laravel-project-setup-for-google-drive-api-integration-part-2 |
|
<?php namespace App\Traits; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Storage; trait WasabiFile { public function saveFile($path, $file) { try { $result = Storage::disk('wasabi')->put($path, fopen($file, 'r')); // return $result; if ($result) { echo "File uploaded successfully."; } else { echo "Failed to upload file."; } } catch (\Exception $e) { Log::error('Wasabi upload failed: ' . $e->getMessage()); echo "Error: " . $e->getMessage(); } } public function deleteFile($filePath) { try { $result = Storage::disk('wasabi')->delete($filePath); if ($result) { echo "File remove successfully."; } else { echo "Failed to remove file."; } } catch (\Exception $e) { Log::error('Wasabi remove failed: ' . $e->getMessage()); echo "Error: " . $e->getMessage(); } } public function bucketName() { try { // API endpoint URL $url = "https://stats.wasabisys.com/v1/standalone/utilizations/bucket"; // Query parameters $queryParams = [ 'pageNum' => 0, 'pageSize' => 1, 'latest' => 'true', 'from' => '1223-12-25', 'to' => '2024-12-25' ]; $AccessKey = env('WAS_ACCESS_KEY_ID'); $SecretKey = env('WAS_SECRET_ACCESS_KEY'); $response = Http::withHeaders([ 'Authorization' => $AccessKey .':'. $SecretKey, // ])->get($url, $queryParams); ])->get($url); // dd($response); if ($response->successful()) { return response()->json($response->json()); } else { return response()->json(['error' => 'Failed to fetch data'], $response->status()); } } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } } |
|
public function itemDelete($model, $id, $tab) { $itemId = DB::table($model)->find($id); if (Schema::hasColumn($model, $column='photo')){ ($itemId->$column!=null) ? (file_exists($itemId->$column) ? unlink($itemId->$column) : '') : ''; } $dbStatus = DB::table($model)->where('id', $id)->delete(); if($dbStatus){ $code = 'success'; $dbOutput = ' delete successfully'; }else{ $code = 'danger'; $dbOutput = ' delete fail'; } $words = explode('_', $model); if (isset($words[1])) { $words[1] = rtrim($words[1], 's'); }else{ $words[0] = rtrim($words[0], 's'); } $model = ucfirst(implode(' ', $words)); return back()->with($code, $model . $dbOutput)->withInput(['tab' => $tab]); } |