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

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

{{  $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(
		'participant'  =>  $participant,
		'userid'  =>  $userid  

Redirect/return-back to the last page from inside a view

<a href="{{ url()->previous()  }}">Back</a>


Chaining where in Eloquent query

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

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', '', '=', 'posts.user_id')
	->join('comments', 'comments.post_id', '=', '')
	->select('', 'posts.title', 'comments.message', ' as post_id')

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