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

To cast a string into Datetime format in controller

date('Y-m-d H:i:s', strtotime($this->document_expiry))

How to retrieve the field value if you have defined an accessor on a Model property

If you have defined an accessor on your Model, every time you access that property, you would get a value through the accessor. Fair enough, that is how it is supposed to work. But there may be times when you want the original property value. How do you get it? By using getAttributes().

Say you have defined an accessor on a property called 2fa in your model so that you get its encrypted value everytime you fetch it like so: $this->user->password. But what if you want to fetch the “unencrypted” value? This is how you get it:

$this->user->getAttributes()['2fa']

If you have defined an accessor such as the following (this returns the value of the “2fa” property encrypted using SHA1)

protected function 2fa(): Attribute
{
	return Attribute::make(
		get: fn (string $value) => sha1($value),
	);
}

Trim a string in Blade

Illuminate\Support\Str::of($product->description)->limit(15)

Capitalize & limit a string in Blade

Illuminate\Support\Str::headline($product->description)->limit(15)

Only limit a string in Blade (and suffix continuation dots)

Illuminate\Support\Str::limit($product->description, 50) . "..."

Setting up a route with parameters

You can call the route from your blade like below and pass the parameter as well. And example of the implementation would be calling details page from a row.

| Name | Age | View CV | |–|–|–| | Tushar | 95 | Link |

<a href="{{ route('success',  [ 'myId'  =>  $collection->id ])  }}">
	Link
</a>

Define your route in routes/web.php

Route::get('/success/{myId}',  [Controller::class,  'save'])->name('success');

You would see that a parameter myId is being passed to the function in your controller. Capture this use this parameter to talk to the DB in your Controller function and pass the collection to the view

public  function save(string  $myId):  View  {
	return view('save',  [
		'myId'  =>  Model::findOrFail($myId)
	]);
}

Now the collection could be used in a view.

Note: Flashing data to session is to be done by chaining with(). The parameters can NOT be passed inside with.

<a href="{{ route('success',  [ 'myId'  =>  $collection->id ])->with('message', 'The data is saved')  }}">
	Link
</a>

The session variable can be accessed like below in the blade.

@if session('message')
	<span>session('message)'</span>
@endif

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

An example of WHERE and WHERE

->where('roles.name',  'Manager')
->where('roles.name',  'Editor');

Two examples of WHERE and (WHERE or WHERE)

->where(function($query)  {
	return  $query->orWhere('roles.name',  'Manager')
	->orWhere('roles.name',  'Editor');
})

->where(function($query)  {
	return  $query->where('users.name',  'LIKE',  '%'  .  $this->searchTerm  .  '%')
	->orWhere('users.email',  'LIKE',  '%'  .  $this->searchTerm  .  '%');
})

use DB::raw to manipulate values of columns at runtime

->select('users.id',  'attempts.start_time',  'attempts.correct_answers',  'quizzes.title',  'attempts.quiz_id',  'attempts.id as attempt_id',  DB::raw('TIMESTAMPDIFF(SECOND,attempts.start_time,attempts.last_response_time) as time_taken_by_user'))

How to get (retrieve) object from an Eloquent relationship

A typical relationship could look like the following in your say order Model

public  function myCustomer():  BelongsTo
{
return  $this->belongsTo(Customer::class,  'customer_id');
}

However if you’d do the typical $order->myCustomer, it would look for the myCustomer property and get you the same. But if you are looking for the model object, first() would help.

$myCustomer  =  $order->myCustomer()->first();

Then you could use it as you may like, for example, in your Notifiable trait on your Model

Notification::send($myCustomer,  new  AckConsentSubmissionNotification($order_mail,  'true'));

Arrays

Using set to create a or add to a nested array

Arr::set($this->userResponses,  $questionID,  []);
Arr::set($this->userResponses,  $questionID,  [$optionValue]);
Arr::set($this->userResponses,  $questionID."2",  []);
Arr::set($this->userResponses,  $questionID."2",  [$optionValue."sec"]);

This will create an array like so:

array:2 [▼ 
  1 => array:1 [▼ 0 => "b" ]
  12 => array:1 [▼ 0 => "bsec" ] ]
comments powered by Disqus