Userful Laravel Code Snippets
Here are a few code snippets that I have found useful time and again
Laravel
Access authenticated user’s ID
Auth::id();
Format date
now()->subDays(1)->format('Y-m-d');
Chaining where
in Eloquent query
Blog::select('id')
->where('date', '<', now()->subDays(1))
->orWhere('some_col', 0)
->get();
Read a file one line at a time and push to an array
$linearray = [];
File::lines(storage_path('logs/'.$logfile))->each(function($line) use(&$linearray) {
$linearray = Arr::prepend($linearray, Arr::get($line, 0));
});
Recursing through a nested JSON structure
foreach ($content -> items as $item => $node) {
Log::info($node->key);
}
Calling an API endpoint with Bearer Token
$response = Http::withToken($accessToken)->get($apiURL, [
'param' => $value,
]);