0

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.

Marshiewooooooo
  • 179
  • 1
  • 2
  • 12
  • This is mostly opinion-based. Something like this possible? Yes of course. You should try it and first before asking in stackoverflow – Shobi Feb 23 '20 at 11:47

2 Answers2

1

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);}}
Sehdev
  • 5,486
  • 3
  • 11
  • 34
0

In your User model you can set accessor.

You may also use accessors to return new, computed values from existing attributes:

/**
 * Get the user's tax payable regarding salary amount.
 *
 * @return float
 */
public function getTaxPayableAttribute()
{
    $taxPayable = 0;
    $taxThreshold = 12000;
    $taxRate = 0.2;
    if ($this->salary >= $taxThreshold) {
        $taxPayable = ($this->salary - $taxThreshold) * $taxRate;
    }
    return $taxPayable;
}

Then simply you can use it as newly computed attrribute:

{{($bob->taxPayable}}

or anywhere in PHP code beside blade file. Docs.

Tpojka
  • 6,996
  • 2
  • 29
  • 39