Userful Laravel Code Snippets

Here are a few code snippets that I have found useful time and again


Access authenticated user’s ID


Format date


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

		->where('date',  '<', now()->subDays(1))
		->orWhere('some_col',  0)

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)  {

Calling an API endpoint with Bearer Token

	$response  =  Http::withToken($accessToken)->get($apiURL, [
		'param' => $value,

**Picking one record from a collection

	{{  $users->first()->email  }}

**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>