John Davidson

php - laravel model constant into controller

0 comments
Message:


I have a model that contains a constant but I want it to move in my controller because the amounts for each key (Basic,Junior,Premium,Advanced,Senior) are being calculated and not fixed. I think moving it inside a controller function I can easily update the amount for each key.


User Model:


protected const AMOUNTS = [
'Basic' => 0,
'Junior' => 100,
'Premium' => 150,
'Advanced' => 200,
'Senior' => 250,
];

and I'm accessing those constants in a function like this


protected function get_amount($rank)
{
$amount = self::AMOUNTS[$rank];
}

I literally don't know how to convert it to fit inside the controller because I want to move in controller because the amount is dynamic and not fixed.


I want something like in my controller


// Controller
public function insert()
{
// Setting the amount for each
$amounts = [
'Basic' => $basic_amount,
'Junior' => $junior_amount,
'Premium' => $premium_amount,
'Advanced' => $advanced_amount,
'Senior' => $senior_amount,
];

// The problem is how to access that, if that's the case?
// I can't do the same with the model using self::AMOUNTS[$rank];
}


My Answer:
[
'Basic' => 100,
'Junior' => 200,
'Premium' => 300,
'Advanced' => 400,
'Senior' => 500
];

public function getAmount($key)
{
return self::AMOUNTS[$key];
}

_Controller:_public function calculateAmount($key)
{
$amount = User::getAmount($key);

// Perform calculations using $amount

return $amount;
}

Rate this post

3 of 5 based on 9886 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us