Dark Mode
Image
  • Wednesday, 10 December 2025
laravel notes

laravel notes

if hkc server down run this cmd
sudo systemctl reload php73-php-fpm ->hkc server

if hr.hkc.ae server down run this cmd
sudo systemctl reload php7.4-fpm ->181(hr.hkc.ae) server






--------------------laravel cmd-----------------------------
composer create-project --prefer-dist laravel/laravel blog

php artisan config:cache

php artisan route:clear

php artisan view:clear

php artisan cache:clear

--------------------laravel cmd-----------------------------


--------------------number mask-----------------------------
<script type='text/javascript' src="https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>
<input type="text" id="Emirates_ID">
$("#Emirates_ID").inputmask("999-9999-9999999-9");
--------------------number mask-----------------------------

--------------------validation-----------------------------
$this->validate($request, [
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($validate->fails()) {
return response()->json(['errors' => $validate->errors()->getMessages()]);
}
--------------------validation-----------------------------

--------------------print error-----------------------------
return Redirect::back()->withErrors(['msg' => 'The Message']);
@if (count($errors) > 0)
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
@endif
--------------------print error-----------------------------

--------------------if ifisset-----------------------------

$a=$b?'kk':'aa';// if

{{$user->email??""}}

$a=$b??'kk'; //ifisset
--------------------if ifisset-----------------------------

 

anas
anas123


--------------------check pc ip-----------------------------
ipconfig --TO check ip address my ip:10.147.27.48
--------------------check pc ip-----------------------------

--------------------data table order-----------------------------
$(document).ready(function() {
$('#example').DataTable( {
"order": [[ 0, "desc" ]] //start with possition 0
} );
} );
--------------------data table order-----------------------------

--------------------laravel Packages-----------------------------
"barryvdh/laravel-dompdf": "^0.8.1",
"dompdf/dompdf": "^0.8.1",
"firebase/php-jwt": "^5.2",
"fx3costa/laravelchartjs": "^2.5",
"guzzlehttp/guzzle": "^6.3",
"hootlex/laravel-moderation": "^1.1",
"intervention/image": "^2.4",
"jenssegers/agent": "^2.6",
"kalnoy/nestedset": "^4.3",
"laravel/framework": "5.5.*",
"laravel/tinker": "~1.0",
"league/oauth2-client": "^2.0",
"niklasravnsborg/laravel-pdf": "^4.0",
"maatwebsite/excel": "^2.1",
"microsoft/microsoft-graph": "1.0.*",
"spatie/laravel-activitylog": "^2.3",
"webklex/laravel-imap": "^2.2",
"wildside/userstamps": "^0.4.0",
"yajra/laravel-datatables-oracle": "^8.0",
"zizaco/entrust": "5.2.x-dev",
"phpoffice/phpspreadsheet": "1.12"

https://www.itsolutionstuff.com/post/how-to-use-yajra-datatables-in-laravel-6example.html

https://www.itsolutionstuff.com/post/laravel-8-pdf-laravel-8-generate-pdf-file-using-dompdfexample.html

https://www.itsolutionstuff.com/post/laravel-57-import-export-excel-to-database-exampleexample.html

https://www.itsolutionstuff.com/post/laravel-8-resize-image-before-upload-exampleexample.html

https://www.itsolutionstuff.com/post/laravel-7-http-client-request-laravel-7-guzzle-http-client-exampleexample.html //composer require guzzlehttp/guzzle

https://www.itsolutionstuff.com/post/how-to-detect-devices-is-mobile-or-desktop-in-laravelexample.html

https://www.itsolutionstuff.com/post/laravel-5-create-dummy-data-using-tinker-factoryexample.html

https://www.itsolutionstuff.com/post/how-to-create-word-document-file-in-laravelexample.html

--------------------laravel Packages-----------------------------

--------------------datatable-----------------------------
$data = mpCandidatesModel::query();

$data = User::with('nationality');
return Datatables::eloquent($data)
--------------------datatable-----------------------------

--------------------DOB-----------------------------
{{\Carbon\Carbon::parse($candidate->date_of_birth)->diffInYears(now())}}
--------------------DOB-----------------------------

--------------------set auth login-----------------------------
Auth::login($user);
--------------------set auth login-----------------------------

--------------------LoadingOverlay-----------------------------
<script src="https://cdn.jsdelivr.net/npm/gasparesganga-jquery-loading-overlay@2.1.7/dist/loadingoverlay.min.js"></script>
$(form).find('[type="submit"]').LoadingOverlay('show');
--------------------LoadingOverlay-----------------------------

--------------------laravel sql-----------------------------
$data = Jobs::where('parent', $user->id)->where('source', 'website')->with(['applications' => function ($q) {
$q->where('application_status', 'New');
}]);


$id = DB::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);

--------------------laravel sql-----------------------------

--------------------base 64 img to image-----------------------------
$data = substr($base64_image, strpos($base64_image, ',') + 1);
--------------------base 64 img to image-----------------------------

--------------------curl file upload-----------------------------
when file upload using curl
CURLOPT_POSTFIELDS => array('File-Name' => 'MSA.pdf','File'=> new CURLFILE('/Users/smusz/OneDrive - Adobe Systems Incorporated/___Public/SendDocs/SendDocs-MSA/_MSA.pdf')),
//if not work use
CURLOPT_POSTFIELDS =>array('File-Name' => $data['File-Name'],'File'=> new \CURLFILE($data['File'])),
--------------------curl file upload-----------------------------

--------------------jwt-token-----------------------------
https://www.avyatech.com/rest-api-with-laravel-8-using-jwt-token/
$user = JWTAuth::authenticate($request->token);
https://laracasts.com/discuss/channels/general-discussion/how-to-refreshing-jwt-token//jwt tocken refresh
--------------------jwt-token-----------------------------

--------------------jquery-confirm-----------------------------
https://craftpip.github.io/jquery-confirm/
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script>
$.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
buttons: {
confirm: function () {
$.alert('Confirmed!');
},
cancel: function () {
$.alert('Canceled!');
},
somethingElse: {
text: 'Something else',
btnClass: 'btn-blue',
keys: ['enter', 'shift'],
action: function(){
$.alert('Something else?');
}
}
}
});
--------------------jquery-confirm-----------------------------


--------------------get value using option value in dropdown-----------------------------


$('select').each(function() {
$(this).find('option[value="2"]').prop('selected', true);
});

--------------------get value using option value in dropdown-----------------------------

 

--------------------Relationship method where method-----------------------------
//mention with in query

if ($request->job) {
$data->whereHas('candidateDetail', function($q) use ($request)
{
$q->where('domestic_work_classification', $request->job);

});
}
--------------------Relationship method where method-----------------------------

--------------------download file /return img-----------------------------

return response()->download($file->path);

return $image->response();
--------------------download file /return img-----------------------------

---------------------------------------------------
to save image from XD
ctrl+E
---------------------------------------------------

---------------------------------------------------
add model table name
protected $table = 'mp_jobs';
---------------------------------------------------

---------------------------------------------------
get key from file
file_get_contents(storage_path('app/sms/maryPoppins.key'))
---------------------------------------------------


-----------------------------------------------------

catch (GuzzleException $e) {
echo $e->getResponse()->getBody()->getContents();
dd("here");
}
------------------------------------------------------

-------------------------------------------------------------
$("body").on('click', 'td [data-online-contract-edit="true"]', function (e) {
var id=$(this).attr('data-id');
$('[data-show="'+id+'"]').show();
$('[data-hide="'+id+'"]').hide();
});
----------------------------------------------------------------


$request = new \Illuminate\Http\Request();
$request->replace(['status' => 'CANCELLED','comment' => 'comment','notifyOthers' => 'false']);
$one = (new ApiController())->updateAgreementStatus($request,$one->unique_id);

-----------------------------------------------------------------------

--------------guzzle multipath file upload-----------------------------
use File;
$request_data['file'] //is normal form submit file
$fileContent = File::get($request_data['file']);

$response = $client->request('POST', $base_url, [
'headers' => $header,
'multipart' => [
[
'name'=>'File-Name',
'contents'=> $request_data['file']->getClientOriginalName(),
],
[
'name'=>'File',
'contents'=>$fileContent,
'filename' => $request_data['file']->getClientOriginalName()
]
],
]);

-----------------------------------------------or------------------------------------------


$file = $request->file('file');

if (!$file) {
return response()->json(['error' => 'No file provided.'], 400);
}

$client = new Client();
$response = $client->post('http://destination-project-url.com/api/receive-file', [
'multipart' => [
[
'name' => 'file',
'contents' => fopen($file->getPathname(), 'r'),
'filename' => $file->getClientOriginalName()
]
]
]);

return response()->json(['message' => 'File sent successfully.', 'response' => json_decode($response->getBody(), true)]);

 

--------------guzzle multipath file upload-----------------------------

----------------------------physical path to normal form submit file-------------------------

change path to physical storage path
$path //file path without base url
$documentPath = storage_path("application/" .$path??'');
$documentPath //get physical path using storage_path

fopen($documentPath, 'r') // its convert physical path to normal form submiting file for multipart

upload image using guzzle multipath

'multipart' => [
[
'name'=>'file',
'contents'=>fopen($documentPath, 'r'),
],
]
--------------------------------physical path to normal form submit file-----------------------

 

-----------------------------------physical path to normal form submit $request file----------------------


use Illuminate\Http\UploadedFile;
$file = new UploadedFile($filePath, basename($filePath));

 

//===============================for live s3========================================
$filePath = $this->cloudStoragePath('CRM/application/recruitment/client/contract/file/Emirates ID/2023/November/joOEIFWUhVONi1KYSOEqRNcXwS4IxBZtGtXHF7Qn.pdf'); // for s3
$fileUrl = Storage::disk("s3")->temporaryUrl($filePath,now()->addMinute(3));
$file_path_temp = $this->cloudCreateTempFile($filePath,$isCloud);
$file = new UploadedFile($file_path_temp, basename($file_path_temp));
//===============================for live s3========================================

//=========================for local==========================================

$filePath = $this->cloudStoragePath('recruitment/client/contract/file/Visa Copy_Passport/2023/November/qF6CgKoIXL2mplNw3uO2To4pUsk7dQIgGOiA8JcY.pdf'); //local
$file = new UploadedFile($filePath, basename($filePath)); //give object like $request->file
dd($file);
//=========================for local==========================================


$request = new \Illuminate\Http\Request();
$request->replace(['source_name' => 'Emirates ID','action'=>'add','fileItem'=>$file]);
$p3_upload_document = new recruitmentDocumentInfoController();
$new_contract_cid = Crypt::encrypt('1591');
$a = $p3_upload_document->fileUploadForAllRecruitment($request,$new_contract_cid);

//app/Http/Controllers/recruitment/renewal/recruitmentRenewalController.php:373

-----------------------------------physical path to normal form submit $request file----------------------

 


-------------guzzel get status code---------------------
$response->getStatusCode()
-------------guzzel get status code---------------------


---------------hide img from chrome---------------------
chrome://settings/content/images?search=Images
---------------hide img from chrome---------------------


--------------run cron in manual------------------------
php .\artisan schedule:run
--------------run cron in manual------------------------

 


--------------this remove closest row------------------------
$("#vaccineTable").on("click", ".remove_vaccine", function() {
$(this).closest("tr").remove();
});
--------------this remove closest row------------------------

------------route accept get post only----------------------

Route::match(['get','post'],'/', 'PRO\envelope\envelopeController@getList')->name('list');

------------route accept get post only----------------------

----------------------validation with soft delete ----------------

unique:tbl_candidates,passport,NULL,candidate_id,deleted_at,NULL

tbl_candidates ->table name
passport ->field name
null -> if null it means create new recode
-> if u edit pass the id
candidate_id ->check field name
deleted_at -> deleted_at field
null -> deleted_at field is null

----------------------validation with soft delete ----------------
----------------------its get only the fillable data----------

$input = $request->only($data->getFillable());
----------------------its get only the fillable data----------


---------------for payroll cal----------------------------
How is Payroll calculated in India?
Net Salary = Gross Salary – Gross Deductions.
here,
Gross Salary = Basic Salary + HRA + All types of Allowances + Reimbursements + Arrears + Bonus.
Gross Deductions = Professional Tax + Public Provident Fund + Income Tax + Insurance + Leave adjustments + Loan repayments (if any)

---------------for payroll cal----------------------------

--------------chunk method------------------------------------
DB::table('users')->chunk(100, function($users)
{
foreach ($users as $user)
{
//
}
return false; //if stop place here
});
--------------chunk method------------------------------------

--------------sql query----------------------------
$query = DB::table('users')->select('name');

$users = $query->addSelect('age')->get();

 

$john = DB::table('users')
->whereIdAndEmail(2, 'john@doe.com')
->whereNameOrAge('Jane', 22)
->first();


$users = DB::table('users')->skip(10)->take(5)->get();

DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();

$user = User::on('mysql_db2')->find(1);

// Retrieve the user by the attributes, or create it if it doesn't exist...
$user = User::firstOrCreate(['name' => 'John']);

User::destroy(1);// using primery key

//default as - deleted_at
u can change
protected $dates = ['deleted_on'];

//get with softdelete data
$users = User::withTrashed()->where('account_id', 1)->get();

User::onlyTrashed()->->where('account_id', 1)->get();

User::withTrashed()->where('account_id', 1)->restore(); //softdel to active data

//9 v
if (DB::table('orders')->where('finalized', 1)->exists()) {
// ...
}

if (DB::table('orders')->where('finalized', 1)->doesntExist()) {
// ...
}

---------------sql query------------------------------------

---------------------------model laravel ------------------------
protected $table = 'my_users';
protected $fillable = ['first_name', 'last_name', 'email'];
protected $guarded = ['id', 'password'];
protected $hidden = ['password'];
protected $visible = ['first_name', 'last_name'];
protected $guarded = ['*'];
public $timestamps = false;
protected $appends = ['is_admin'];
protected $casts = [
'is_admin' => 'boolean',
'options' => 'array',
];
-------
use Illuminate\Support\Str;
Str::random(10)
-------------
class User extends Model {

public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}

public function scopeWomen($query)
{
return $query->whereGender('W');
}

}
$users = User::popular()->women()->orderBy('created_at')->get();
-----------
class User extends Model {

public function phone()
{
return $this->hasOne('App\Phone');
}

}
$phone = User::find(1)->phone;

select * from users where id = 1

select * from phones where user_id = 1

return $this->hasOne('App\Phone', 'foreign_key');

FOR THIS (TOP) WE USE THIS(DOWN)

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
----------

return $this->belongsTo('App\User');

return $this->hasMany('App\Comment');

return $this->belongsTo('App\Post');

return $this->belongsToMany('App\Role');

return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'foo_id');//DOUBT
----------------
countries
id - integer
name - string

users
id - integer
country_id - integer
name - string

posts
id - integer
user_id - integer
title - string

class Country extends Model {

public function posts()
{
return $this->hasManyThrough('App\Post', 'App\User');
}

}

class Country extends Model {

public function posts()
{
return $this->hasManyThrough('App\Post', 'App\User', 'country_id', 'user_id');
}

}
-------------------------------------
$posts = Post::has('comments')->get();
$posts = Post::has('comments', '>=', 3)->get();

$posts = Post::whereHas('comments', function($q)
{
$q->where('content', 'like', 'foo%');

})->get();

------------
$books = Book::all();

$books->load('author', 'publisher');
-----------
$comment = new Comment(['message' => 'A new comment.']);

$post = Post::find(1);

$comment = $post->comments()->save($comment);

$post->comments()->saveMany($comments);//if u have an array more then one
--------------------
$roles = User::find(1)->roles->toArray();

$roles = User::find(1)->roles->toJson();
------------------

------------------laravel-debugbar-----------------
composer require barryvdh/laravel-debugbar --dev
Barryvdh\Debugbar\ServiceProvider::class,
'Debugbar' => Barryvdh\Debugbar\Facades\Debugbar::class,
composer update
php artisan cache:clear
php artisan config:cache
APP_DEBUG=true
------------------laravel-debugbar-----------------

-----------------------default login---------------------
"laravel/ui": "^3.4", //for automatic login route
// in web.php declear Auth::routes();

----------------------------default login------------------


----------------------------new php version------------------

-composer
C:\xampp\php-8.1\php C:\xampp\htdocs\composer.phar require laravel/ui

-artisan
C:\xampp\php-8.1\php artisan vendor:publish --tag="LaravelEntrust"

C:\xampp\php-8.1\php artisan serve --port 8000

C:\xampp\php-8.1\php artisan config:cache
C:\xampp\php-8.1\php artisan serve --port 8000

-composer update
C:\xampp\php-8.1\php C:\xampp\htdocs\composer.phar update

 


----------------------------new php version------------------

---------------------------where json ------------------------
$users = DB::table('users')
->whereJsonLength('options->languages', '>', 1)
->get();
$users = DB::table('users')
->whereJsonContains('options->languages', 'en')
->get();
---------------------------where json ------------------------

-------------------------select2 pass data----------------------

data: function (params) {
return {
product_id: $('#product_id').val(),
};
},
-------------------------select2 pass data----------------------

-------------------------datatable pass data----------------------

ajax: {
url: '{!! request()->url() !!}',
data: function (d) {
d.daterange = $('#dateRange').val();
}
},
-------------------------datatable pass data----------------------


-------------------------print log----------------------

print datat in laravel.log
use Illuminate\Support\Facades\Log;
Log::info("i am every minutes".now()->toDateTimeString());

-------------------------print log----------------------


-------------------------construcrt auth can----------------------
public function __construct()
{
$this->middleware(function ($request, $next) {
if(Auth::user()->can('sales-reports-sales-by-coordinator')){
return $next($request);
}
abort(404);
});
}
-------------------------construcrt auth can----------------------

-------------------------pagination in mobile api----------------------

return new JobsCollection($data->paginate(10));

--in jobscollection page--

public function toArray($request)
{
return [
'status' => "Success",
'data' => JobsResource::collection($this->collection),
'pagination' => [
'path' => url()->current(),
'first_page_url' => $this->url(1),
'last_page_url' => $this->url($this->lastPage()),
'next_page_url' => $this->nextPageUrl(),
'prev_page_url' => $this->previousPageUrl(),
'from' => $this->currentPage(),
'last_page' => $this->lastPage(),
'per_page' => $this->perPage(),
'to' => $this->count(),
'total' => $this->total(),
]
];
}

public function withResponse($request, $response)
{
$jsonResponse = json_decode($response->getContent(), true);
unset($jsonResponse['links'],$jsonResponse['meta']);
$response->setContent(json_encode($jsonResponse));
}

-------------------------pagination in mobile api----------------------


-------------------------model overwrite----------------------

protected $primaryKey = "id";
const CREATED_AT = "created_on";
const UPDATED_AT = "modified_on";

-------------------------model overwrite----------------------


-------------------------update laravel version----------------------

/config/session.php
-> 'secure' => env('SESSION_SECURE_COOKIE', null), at line 167
/composer.json
->pls refer laravel 8 framework or refer mypoppin
/app/Exceptions/Handler.php
-> instance of Exception use Throwable
->use Throwable;
->change every where Exception to Throwable in that page


->if showing error in passport while composer update remove class in config/app.php and if passport exist authserviceprovider.php remove and do composer update
->just remove the unknow version package then update composer after composer update install the package one by one

-------------------------update laravel version----------------------


-------------------------mysqlerror----------------------------------
mysqlerror.
Error: MySQL shutdown unexpectedly.
https://stackoverflow.com/questions/18022809/how-to-solve-error-mysql-shutdown-unexpectedly
-------------------------mysqlerror----------------------------------
--------------------get extra values from select2drop down and assign to textbox-------------------------------

$("#recruitment_batch").select2({
width: "100%",
minimumResultsForSearch: -1,
placeholder: "Select Recruitment Batch",
ajax: {
url: '{{route("philippine-placement-agency-candidate-return-get-candidates")}}',
dataType: 'json',
type: "GET",
delay: 250,
data: function (term) {
return {
term: term,
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
// return {
// text: 'RB'+item.id,
// id: item.id,
// full_name: item.first_name + ' ' + item.last_name,
// cn_id: item.cn_id,
// }
return {
text: item.id+'-'+item.first_name + ' ' + item.last_name,
id: item.id,
full_name: item.first_name + ' ' + item.last_name,
cn_id: item.cn_id,
}
})
};

}
}
}).on('select2:select', function (e){
$data = e.params.data;
$('[name="cn_name"]').val($data.full_name);
$('[name="cn_id"]').val($data.cn_id);
});
--------------------get extra values from select2drop down and assign to textbox-------------------------------


--------------------------------------ADD EXTRA FIELDS IN DATA SET------------------


$pending->map(function ($data) {
if($data->job){
$data->job->job_img = $data->job->getJobImage();
$data->job->posted_on = Carbon::parse($data->job->created_at)->format('d-m-Y'); //need to discuss for show job active date

$data->job->job_status = false;
if($data->job->till_date){
$result = Carbon::createFromFormat('Y-m-d', $data->job->till_date)->gte(Carbon::now());
$data->job->job_status = $result;
}
}
});
--------------------------------------ADD EXTRA FIELDS IN DATA SET------------------


----------------------------------------cmd for cp file----------------------------------------------
login to filezilla
login to putty
put file in /home/sysadmin
give the destination path and run


sudo cp /home/sysadmin/app.css /var/www/housekeepingco.com/public/css/maid_residency/

copy and move folder
sudo cp -r /home/sysadmin/cefr /var/www/domesticworker.ae/public/images/
(cefr is the folder copyed to inside images folder)

 

---------------------------------------cmd for cp file-----------------------------------------------

-----------------hr excel export code --------------------------------------

$output= Excel::create('report'.date('Ydmhsi'), function($excel) use($array){
$excel->sheet('HRM-CN', function($sheet) use($array){
$i = 0;
$sheet->fromArray($array);
});
$excel->getDefaultStyle()->applyFromArray(array('wrap' => TRUE));
});
$files= $output->store("xlsx",false,true)['full'];
return response()->download($files);

-----------------hr excel export code --------------------------------------

 

https://helpx.adobe.com/ae_en/sign/using/adobesign-lock-user-name-values.html


---------------------------------------------------------------------------------


$flights = $flights->reject(function ($flight) {
return $flight->cancelled;
});
------------------------------------------------------
Flight::chunk(200, function ($flights) {
foreach ($flights as $flight) {
//
}
});
-------------------------------------------------------
use App\Models\Flight;

foreach (Flight::lazy() as $flight) {
//
}

foreach (Flight::where('destination', 'Zurich')->cursor() as $flight) {
//
}

 

 

 

$opt = isset($docs)?["parent"=>$enid]:[];
$imageid = $ufile->upload_file_laravel((object)[
"table_name"=>recruitmentEnquiry::class,
"name"=>$file->getClientOriginalName(),
"source"=>$fileSource,
"document"=>$file,
"module"=>json_encode(array("recruitment"=>array("client"=>array("contract"=>array("file"=>[$source]))))),
"module_json"=>"true",
"permission"=>"recruitment-client-contract",
"response_type"=>"id",
"parent"=> $enid,
"description"=>" ",
"type"=>$file->getClientMimeType()
],($docs->id)??null,$opt);
---------------------------------------------------------------------------------

 


-----------------------------------config clear in our live crm server----------------------------------------------

config clear in our live crm server
php73 artisan config:clear


-----------------------------------config clear in our live crm server----------------------------------------------

 

 

 

-----------------------------------crop image based on possition and converted to normal form submit file----------------------------------------------
$coordinates = $request->coordinates;
$coordinatesArr = explode(',', $coordinates);


$width = (int)round($coordinatesArr[2] - $coordinatesArr[0]);
$height = (int)round($coordinatesArr[3] - $coordinatesArr[1]);
$co_x = (int)round($coordinatesArr[0]);
$co_y = (int)round($coordinatesArr[1]);


//code block start: updated by mukesh
$extension1 = $file->getClientOriginalExtension();

$profile_photo = Image::make($request->file('profile_image'));
$profile_photo->orientate();
$profile_photo1 = $profile_photo->crop($width, $height, $co_x, $co_y);
$file_path = '/cn_profile_photo/' . $cn_id . '.' . $extension1;

Storage::disk('public')->put($file_path, $profile_photo1->encode());
$documentPath = storage_path("app/public" .$file_path??'');
$file = new UploadedFile($documentPath, basename($documentPath));
$file // is equal to $request->file normal form submit formate
-----------------------------------crop image based on possition and converted to normal form submit file----------------------------------------------

 

-----------date to time stamp using carbon------------------------

$created_at_time_stamp = Carbon::parse($one_data->created_at)->timestamp;
$created_at_date = Carbon::createFromTimestamp($created_at_time_stamp);
dd($one_data->created_at,$created_at_time_stamp,$created_at_date);


-----------date to time stamp using carbon------------------------

 

-------------------------------base64 encode decode with key (short encrypt string)-----------------------------


$encrypted = encrypt("to encrypt string", "secret key");
echo $encrypted ;
$decrypted = decrypt($encrypted, "secret key");

echo $decrypted ;


function encrypt($string, $key) {
$result = '';
for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)+ord($keychar));
$result.=$char;
}

return base64_encode($result);
}

function decrypt($string, $key) {
$result = '';
$string = base64_decode($string);

for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)-ord($keychar));
$result.=$char;
}

return $result;
}

-------------------------------base64 encode decode with key (short encrypt string)-----------------------------


-------------to send file to another project using api guzzle--------------------
use File:
$fileContent = File::get($fileObject);
$postResponse = $http->post($url, [
'multipart' => [
[
'name'=>'nanny_eid',
'contents'=>$fileContent,
/*for passing real attachment name*/
'filename' => $fileObject->getClientOriginalName()
]
],
]);
-------------to send file to another project using api guzzle--------------------

--------------laravel Observers (after changes in the db this event will trigger)----------------------

using this cmd to create observer
location -->app/Observers/ProductObserver.php
php artisan make:observer ProductObserver --model=Product


and menction observer in eventserviceprovider
location->app/Providers/EventServiceProvider.php
public function boot()
{
Product::observe(ProductObserver::class);
}

reference ->https://www.itsolutionstuff.com/post/how-to-use-laravel-model-observersexample.html#google_vignette

--------------laravel Observers (after changes in the db this event will trigger)----------------------

to check zip is installed or not
zip --version

If it's not installed, you can install it with:
sudo apt-get install zip

zip the folder open the path then run below cmd
zip -r my_folder.zip my_folder

Include Hidden Files: If you want to include hidden files (files starting with .) in the zip file, you can use:
zip -r output_name.zip folder_name/*

Excluding Files: To exclude specific files or folders while zipping, use the -x option:
zip -r output_name.zip folder_name -x "*.log"

to unzip
unzip file.zip

=====================================json response to array====================


$position_added = $this->addSelect2Item($request); // return json
$position_added = $position_added->getContent(); // convert to proper json
$position_addedd = json_decode($position_added,true); // convert to array

=====================================json response to array====================


==========================form data==============================
$client = new Client();
$url = 'https://dataapi.octoparse.com/token';

$response = $client->post($url, [
'verify' => false,
'form_params' => [
'username'=>'testm',
'password'=>'test@2025',

],
]);

$body = $response->getBody()->getContents();
$responseData = json_decode($body, true);


==================if json==============
'form_params' => [
'username'=>'testm',
'password'=>'test@2025',

],
===============if json================

==============================form data ==============================

=====================for table draw=====================

To redraw datatable without lossing current page
use this
table.page(table.page()).draw(false);

instead to call this
table.draw();
=====================for table draw=====================

Tags

Comment / Reply From

Newsletter

Subscribe to our mailing list to get the new updates!