I’m new to Blade and wondering where should I have the logic for creating a phone link - could you guys help me?
I want to use @nathobson code and display an anchor with a phone number in a few different partials, the phone is stored on an ACF options page and has to be sanitized before inserting it to an anchor.
A nice and easy way to do this would be with a controller.
In app/Controllers/App.php, inside the App class, add something like:
public function phone() {
// Initialize the return variable
$return = '';
// Get the phone number from the ACF options field
$number = get_field(‘phone’, ‘option’);
// Sanitize the phone number!
$return = '+1' . preg_replace("/[^0-9]/", “”, $number);
// Always return
return $return;
}
Because since this anchor will be displayed in a few partials writing this everywhere doesn’t seem DRY.
I would normally make a function that returns the whole anchor including the HTML and add it to the partial using
@php echo function() @endphp
but after reading a bunch of topics here I don’t think you guys do it like that, and this one line of code seems too small to put it in a separate partial.
Hi, @mefusia,
If the phone number component is truly as reusable as you say, I would make it into its own partial. I prefer not to have HTML outside of my templates.
It’s totally your call. If writing HTML with the function makes sense to you, then go for it.
But even then, I would write it all as a controller function as follows:
public function phone() {
// Initialize the return variable
$return = '';
// Get the phone number from the ACF options field
$number = get_field(‘phone’, ‘option’);
// Sanitize the phone number!
$output = '+1' . preg_replace("/[^0-9]/", “”, $number);
// Only output HTML if there was a number to work with
if(isset($number) {
$return = "<a href=\"tel://" . $output . "\">Call Me</a>";
}
// Always return
return $return
}
And then add it to your template like this:
{{ $phone }}
That way you’re keeping your PHP and logic out of your templates.