Useful Laravel Code Snippets

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

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

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 a column value from a record

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

Eloquent

Chaining where in Eloquent query

Blog::select('id')
	->where('date',  '<', now()->subDays(1))
	->orWhere('some_col',  0)
	->get();

Find multiple IDs given in a array in a table and retrieve models

$posts  =  [10,11];
$records  =  Question::select('title',  'name',  'author')->find($posts);

Using Join

$records = DB::table('users')
	->join('posts', 'users.id', '=', 'posts.user_id')
	->join('comments', 'comments.post_id', '=', 'posts.id')
	->select('users.id', 'posts.title', 'comments.message', 'posts.id as post_id')
	->get();

// usage in blade
{{ $record->title }} 
{{ $record->post_id }}