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');
Converting Linux datestamp to normal date format (in Blade)
\Carbon\Carbon::parse($subInfo->current_period_end)->isoFormat('MMM Do YYYY')
[in controller]
$expires_at = date('Y-m-d H:i:s', $datestamp);
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,
]);
**Picking one record from a collection
{{ $users->first()->email }}
Returns
**Redirect with parameters from inside a controller
return redirect('dashboard')->with([
'status' => '200',
'msg' => $request->user . ' added successfully'
]);
**Redirect/return-back to the last page with parameters inside a controller
return back()->with([
'userid' => $request->user_id,
'status' => '200',
'msg' => $request->name . ' added successfully'
]);
**Return to a view from inside a controller
return view('contest-registrations/update-participant',
[
'participant' => $participant,
'userid' => $userid
]
);
**Redirect/return-back to the last page from inside a view
<a href="{{ url()->previous() }}">Back</a>