Laravel
Just some random useful Laravel tricks:
Get some headers
// All headers in the request:
$request->headers->all();
// Get specific header 'user-agent':
$request->header('user-agent')
Check the database connection
php artisan tinker
DB::connection()->getPdo();
Here's a way to use a composer library locally and be able to make edits.
Keep in mind that this is not allways the best approach. A forked repo could be a better solution.
There's some more info here:
https://getcomposer.org/doc/05-repositories.md#loading-a-package-from-a-vcs-repository
Here are the required changes in composer.json:
"require": {
"beyondcode/laravel-websockets": "*",
...
}
"repositories": [
{
"type": "path",
"url": "packages/laravel-websockets"
}
],
Use carbon to get a time difference:
Carbon::parse('19851017')->diff(Carbon::parse('20221017'))->format('%y years, %m months and %d days');
Eloquent search by date using Carbon:
$query->whereDate('created_at' , '=', Carbon::today()->subDays( 2 ));
Check if the current date is in a given timezone:
$isPromo => Carbon::now()->setTimezone('America/Los_Angeles')->isBetween('2021-07-29 00:00:00', '2021-08-31 23:59:59'),
Use Carbon to convert a date from users timezone to UTC and perform an Eloquent search between two dates:
$user = Auth::user();
$startDate = Carbon::parse('2017-11-27 00:00:00', $user->timezone)->setTimezone('UTC');
$endDate = Carbon::parse('2017-12-29 23:59:59', $user->timezone)->setTimezone('UTC');
$user->events()
->whereBetween('created_at', [$startDate, $endDate])
->get('name');
Eloquent search in JSON column:
User::where('settings->auto_archive_sessions', '>', 0)->get(['id', 'settings->auto_archive_sessions as days'])->toArray();
Search LIKE using Eloquent:
BookingDates::where('email', Input::get('email'))
->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();
Dump Eloquent query with parameters (bindings):
$query = Session::where('profile_id', $profileId)
->where('is_archived', $isArchived);
dd( vsprintf( str_replace(['?'], ['\'%s\''], $query->toSql()) , $query->getBindings() ) );
Get the query used to create a table:
DB::table('users')->toSql()
Check if requested URL matches something specific within a blade template:
@if(request()->is('profile')) active-tab @endif
Order by multiple columns:
$consumables = Consumable::orderBy('weight')->orderBy('id')->get()->pluck("consumable.".App::getLocale(), 'id');
Get JSON response from API ignoring the SSL certificate:
$response = Http::withoutVerifying()->get($url)->json();
Get the response body as string:
$response = Http::get($url);
$response->getBody()->getContents();