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

Tailwind CSS

Button as link in blade

	<button class="bg-sky-400 hover:bg-sky-600 mt-4 px-4 py-2 rounded-md text-white">
		<a href="{{ route('dashboard')  }}">Dashboard</a>
	</button>

Flex centering of icon and text

	<div class="flex items-center">
		<svg xmlns="http://www.w3.org/2000/svg"  fill="none"  viewBox="0 0 24 24"  stroke-width="1.5"  stroke="currentColor"  class="w-4 h-4">
			<path stroke-linecap="round"  stroke-linejoin="round"  d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15m3 0l3-3m0 0l-3-3m3 3H9"  />
		</svg>

		<span class="pl-2">
			Settings
		</span>
	</div>