1. Go to this page and download the library: Download maksimru/multi-unit-models library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
namespace MaksimM\MultiUnitModels\Tests\Models;
use Illuminate\Database\Eloquent\Model;
use MaksimM\MultiUnitModels\Traits\MultiUnitSupport;
use UnitConverter\Unit\FuelEconomy\KilometrePerLitre;
use UnitConverter\Unit\FuelEconomy\LitrePer100Kilometres;
use UnitConverter\Unit\FuelEconomy\MilesPerGallon;
use UnitConverter\Unit\Length\Kilometre;
use UnitConverter\Unit\Length\Mile;
class Vehicle extends Model
{
use MultiUnitSupport;
public $incrementing = true;
protected $primaryKey = 'vehicle_id';
protected $table = 'vehicles';
public function getMultiUnitColumns()
{
return [
//column name
'height' => [
//default unit (value will be stored in DB in specified default units)
'default_unit' => Kilometre::class,
//additional units that you want to have in your application
'supported_units' => [
Kilometre::class,
Mile::class,
]
],
'fuel_consumption_city' => [
'default_unit' => LitrePer100Kilometres::class,
'supported_units' => [
LitrePer100Kilometres::class,
KilometrePerLitre::class,
MilesPerGallon::class,
]
],
];
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'height',
'fuel_consumption_city',
];
}
$model = Vehicle::create([
'name' => 'test',
'fuel_consumption_city' => '5'
]);
// fuel_consumption_city is set to 5 L/100Km
$model = Vehicle::selectedUnits([
'fuel_consumption_city' => 'mpg'
])->create([
'name' => 'test',
'fuel_consumption_city' => '5',
]);
// fuel_consumption_city is set to 5 mpg and DB will have fuel_consumption_city 47.04 (default units L/100Km), $model->fuel_consumption_city will return 5 (MPG)
$model->update([
'fuel_consumption_city' => '1',
]);
// fuel_consumption_city is set to 1 mpg and DB will have fuel_consumption_city 235.215 (default units L/100Km), $model->fuel_consumption_city will return 1 (MPG)
$model->setMultiUnitFieldSelectedUnit('fuel_consumption_city', 'L/100km');
$model->update([
'fuel_consumption_city' => '1',
]);
// fuel_consumption_city is set to 1 L/100Km