Ad

What Is The Correct Way To Perform A Formula In Laravel 6 Without Repeating The Formula Each Time?

In the database I have a salary for each of my staff.

I need to work out how much tax to deduct from the salary, but I don't think I would be correct to hardcode this into each view, something like...

{{($bob->salary - 12,000) * 0.2}}

It's obviously messy and repeated.

What I think I need to do is create a function where I can simply feed Bob's salary, it calculates the tax and returns the value.

Something like...

public function taxPayable($salary){
  $taxThreshold = 12,000;
  $taxRate = 0.2;
  if($salary >= $taxThreshold){
    $taxPayable = ($salary - $taxThreshold) * $taxRate;
  } else {
    $taxPayable = 0;
  }
  return $taxPayable;
}

Then simply..

{{Taxcalculator::taxPayable($bob->salary)}}

Would something like this be possible? Where would I put the function, in a controller or model? Obviosuly the code wouldn't work but just to show what I want to achieve, just wondering how I would achieve it, is this possible? thanks.

Ad

Answer

You can create a custom Helper class and use that in your Controller to perform the same:

Step 1: Create your Helpers (or other custom class) file and give it a matching namespace. Write your class and method:

<?php // Code within app\Helpers\Helper.php

namespace App\Helpers;

class Helper
{
    public static function taxPayable($salary)
    {
         // perform your calculation here
        return $taxPayable;
    }
}

Step 2: Create an alias:

<?php // Code within config/app.php

    'aliases' => [
     ...
        'Helper' => App\Helpers\Helper::class,
     ...

Step 3: Run composer dump-autoload in the project root

Step 4: Use this class anywhere in your Laravel app:

<?php // Code within app/Http/Controllers/SomeController.php

namespace App\Http\Controllers;

use Helper;

class SomeController extends Controller
{

    public function __construct()
    {
        Helper::taxPayable($bob->salary);
    }

Even you can use this in your view also like:

{{Helper::taxPayable($bob->salary);}}
Ad
source: stackoverflow.com
Ad