I need to store interest_amount which is computed using get_Attribute function however now I need to insert it into table.
I have used static::saving function to compute interest_amount I don't know how to call it using $data in controller
Loan.php
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $fillable = [
'amount',
'interest',
'status',
'duration',
'member_id',
'loan_type_id',
'interest_type_id',
'loan_payment_type_id'
];
protected $appends = 'interest_amount';
public function getInterestAmountAttribute()
{
return ($this->amount)/100 * $this->interest;
}
public function member()
{
return $this->belongsTo(Member::class,'member_id','id');
}
protected static function boot()
{
parent::boot();
static::saving(function($model) {
$model->interest_amount = ($model->amount/100 ) * $model->interest;
});
}
}
LoanController.php
$data['amount'] = $request->amount;
$data['interest'] = $request->interest;
$data['interest_amount'] = $interest_amount;
$data['duration'] = $request->duration;
$data['status']= $request->status;
$data['member_id'] = $request->name;
$data['loan_type_id']= $request->loan_type;
$data['interest_type_id']= $request->interest_type;
$data['loan_payment_type_id']= $request->payment;
if(DB::table('loans')->insert($data)){
return redirect()->route('loan')->with('success','data was successfuly inserted');
}
I initially didn't have interest_amount column but I added it later. I don't know how to call the saving function with the approach I have used in my controller.
Model events will not fire when you use the query builder to insert data into your tables.
You have to use the Model to save the data, something like this:
If your model attributes are mass assignable:
if((new Loan($data))->save()){
return redirect()->route('loan')->with('success','data was successfuly inserted');
}
otherwise:
$loan = new Loan;
$loan->amount = $request->amount;
$loan->interest = $request->interest;
$loan->interest_amount = $interest_amount;
$loan->duration = $request->duration;
$loan->status = $request->status;
$loan->member_id = $request->name;
$loan->loan_type_id = $request->loan_type;
$loan->interest_type_id = $request->interest_type;
$loan->loan_payment_type_id = $request->payment;
if($loan->save()){
return redirect()->route('loan')->with('success','data was successfuly inserted');
}
Related
I have issue in handling json multiple data. I am not getting multiple data and if I use "array" then also it creates single record with null values in database.
The Backend code for saving data
{
$pickup = new PickupData();
$pickup->pickup_person = $request->pickup_person;
$pickup->office_city = $request->office_city;
$pickup->office_state = $request->office_state;
$pickup->office_pincode = $request->office_pincode;
$pickup->pickup_email = $request->pickup_email;
$pickup->preferred_start_time = $request->preferred_start_time;
$pickup->preferred_end_time = $request->preferred_end_time;
$pickup->mobile = $request->mobile;
$pickup_date = Carbon::parse($request->pickup_date)->format('d-m-Y');
$pickup->pickup_date = $pickup_date;
$saved = $pickup->save();
}
I need response like and it should be saved into database
[
{
"pickup_person":"SanPune6",
"city":"pune",
"office_address":"viman nagar",
"office_city":"Pune",
"office_state":"MH",
"office_pincode":"121212",
"pickup_email":"office#gmail.com",
"preferred_start_time":"12:38:29",
"preferred_end_time":"13:02:33",
"mobile":"9090909090",
"pickup_date":"12-04-2019"
},
{
"pickup_person":"SanPune6",
"city":"pune",
"office_address":"viman nagar",
"office_city":"Pune",
"office_state":"MH",
"office_pincode":"121212",
"pickup_email":"office#gmail.com",
"preferred_start_time":"12:38:29",
"preferred_end_time":"13:02:33",
"mobile":"9090909090",
"pickup_date":"12-04-2019"
}
]
create resource sth like this
php artisan make:resource PickupResourceCollection
create another resource sth like
php artisan make:resource PickupResource
in your index method of PickupController do sth like this
use use App\Http\Resources\PickupResourceCollection;
...
public function index()
{
$pickups = Pickup::all();
return response()->json(new PickupResourceCollection($pickups),200);
}
...
in PickupResourceCollection do sth like this
....
public function toArray($request)
{
return [
'data' => $this->collection->transform(function ($pickups) {
return new PickupResource($pickups);
})
];
}
....
in PickupResource do sth like this
....
public function toArray($request)
{
return [
"pickup_person" =>$this->pickup_person,
"city" =>$this->city,
"office_address" =>$this->office_address,
"office_city" =>$this->office_city,
"office_state" =>$this->office_state,
"office_pincode" =>$this->office_pincode,
"pickup_email" =>$this->pickup_email,
"preferred_start_time"=>$this->preferred_start_time,
"preferred_end_time" =>$this->preferred_end_time,
"mobile" =>$this->mobile,
"pickup_date" =>"$this->pickup_date
];
}
....
thats it :)
Yes you can save by as an array.
$pickup = PickupData::create($request->all()) // to save all request data
$pickup = PickupData::create($request->except(['var1', 'var2'])) // to save all request data except var1 & var2
$pickup will return only newly inserted row.
$pickupDetails = [
{
"pickup_person":"SanPune6",
"city":"pune",
"office_address":"viman nagar",
"office_city":"Pune",
"office_state":"MH",
"office_pincode":"121212",
"pickup_email":"office#gmail.com",
"preferred_start_time":"12:38:29",
"preferred_end_time":"13:02:33",
"mobile":"9090909090",
"pickup_date":"12-04-2019"
},
{
"pickup_person":"SanPune6",
"city":"pune",
"office_address":"viman nagar",
"office_city":"Pune",
"office_state":"MH",
"office_pincode":"121212",
"pickup_email":"office#gmail.com",
"preferred_start_time":"12:38:29",
"preferred_end_time":"13:02:33",
"mobile":"9090909090",
"pickup_date":"12-04-2019"
}
];
$pickupDetails = $request->all();
foreach($pickupDetails as $pickup){
Pickup::create($pickup);
}
return response()->json("success",200);
if it helps you upvote me :)
thats the controller
public function hitung($request, $response, $args)
{
$datauser = User::with(['usia','aktivitas'])->find($args['id']);
$tinggi = $datauser['tinggi'];
$berat = $datauser['berat'];
$nama = $datauser['nama'];
$umur = $datauser['umur'];
$aktivitas = $datauser['aktivitaas_id'];
$usia = $datauser['usia_id'];
$nilai = $datauser->aktivitas->nilai;
$energy = $datauser->usia->energy;
$protein = $datauser->usia->protein;
$lemak = $datauser->usia->lemak;
$karbohidrat = $datauser->usia->karbohidrat;
$amb = 655 + (9.6 * $berat) + (1.8 * $tinggi) - (4.7 * $umur);
$amb = round($amb);
$energytotal = $amb * $nilai + $energy;
$energytotal = round($energytotal);
$protein = (15 * $energytotal / 100) + $protein;
$protein = round($protein);
$lemak = (25 * $energytotal / 100) + $lemak;
$lemak = round($lemak);
$karbohidrat = ($energytotal - ($protein + $lemak)) + $karbohidrat;
$karbohidrat= round($karbohidrat);
return $response ->withJson([
'Nama' => $nama,
'total_energy' => $energytotal ,
'Protein'=> $protein,
'lemak'=> $lemak,
'Karbohidrat'=> $karbohidrat,
]);
}
thats the user model:
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $timestamps = false;
protected $fillable = ['username', 'password', 'nama', 'tinggi', 'berat', 'umur', 'usia_id', 'aktivitas_id'];
protected $table = "users";
public function usia()
{
return $this->belongsTo('App\Models\Usia');
}
public function aktivitas()
{
return $this->belongsTo('App\Models\Aktivitas');
}
public function forum()
{
return $this->hasMany('App\Models\Forum');
}
}
thats the aktivitas model:
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class Aktivitas extends Model
{
protected $table = "aktivitas";
public function user()
{
return $this->hasMany('App\Models\User');
}
}
thats the usia model ,
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class Usia extends Model
{
protected $table = "usia";
public function user()
{
return $this->hasMany('App\Models\User');
}
}
this code is work in local , but when i hosting it , it didnt work , please need help for my exam ...
i think the problem is in this code ,
$datauser = User::with(['usia','aktivitas'])->find($args['id']);
any different way to do it ?
I guess your local is Windows and remote host is Linux
first of all you should know windows file and folder name is not case sensitive and there is no different between Models and models in windows OS
but Linux file and directory name is Case Sensitive
in your codes:
namespace App\models;
and
return $this->hasMany('App\Models\User');
somewhere you use Models and models
you should check directory name and rename it anywhere you write wrong word
It's been several days since I've been blocking to persist items from an order into session to database.
I stock articles in session in an array and I do not know how to persist the array. I try to convert the array into an object, I can not. This is my service:
public function addArticle($id)
{
$sessionCart = $this->session;
$article = $this->doctrine->getRepository('AppBundle:Article')->find($id);
$cart = $sessionCart->get('cart');
$cart[] = $article;
$sessionCart->set('cart', $cart);
// use later for delivery
$sessionCart->get('commande');
return $sessionCart;
}
public function panier()
{
$articles = $this->session->get('cart');
return $articles;
}
public function delivery(Request $request)
{
$commande = new Commande();
$articles = $this->session->get('cart');
$form = $this->form->create(CommandeType::class, $commande);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid())
{
$data = $form->getData();
$this->session->set('commande', $data);
$response = new RedirectResponse('payment');
$response->send();
}
return [$form, $articles];
}
public function payment(Request $request)
{
$articles = $this->session->get('cart');
$commande = $this->session->get('commande');
if ($request->isMethod('POST')) {
$em = $this->doctrine;
$em->persist($articles);
$em->persist($commande);
$em->flush();
}
return[$articles, $commande];
}
Error : "EntityManager#persist() expects parameter 1 to be an entity object, array given."
The order is persisted but not the items.
Thanks
I can't understand these two lines
$cart = $sessionCart->get('cart');
$cart[] = $article;
$sessionCart->set('cart', $cart);
$cart is an array and should be an entity isn't it ?
The persist is waiting for an entity,
maybe you can persist in a foreach loop:
foreach($articles as $article){
$em->persist($article);
}
or use a doctrineCollection instead of an array
I want to insert multiple record in my table using yii2 ActiveRecord.
I already know that I can use this code
$connection->createCommand()->batchInsert('user', ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
])->execute();
but by this approach my model validations are not executing.
and I already have read this question
ActiveRecord batch insert (yii2)
but also by doing validation in a tricky way, consider I want to fill created_at and updated_at columns using ActiveRecords events.
just like this
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if($insert)
$this->created_at = date('Y-m-d H:i:s');
$this->updated_at = date('Y-m-d H:i:s');
return true;
} else {
return false;
}
}
I think is not good idea to use beforeSave events (and similar stuff) because it will trigger for each model. However you want save multiple models at once. I recommend to use bulk methods.
In similar cases I use usually following "bulk" approach (code not tested, just for example):
namespace common\components;
class Model extends yii\base\Model {
/**
* Saves multiple models.
*
* #param ActiveRecord[] $models
* #return bool
*/
public static saveMultiple($models){
if(count($models) > 0){
$firstModel = reset($models);
$columnsToInsert = $firstModel->attributes(); // here you can remove excess columns. for example PK column.
$modelsToInsert = [];
$rowsToInsert = [];
foreach($models as $model){
if ($this->beforeSave(true)) {
$modelsToInsert[] = $model;
}
}
foreach($modelsToInsert as $model){
$rowsToInsert[] = array_values($model->attributes); // here you can remove excess values
}
$numberAffectedRows = \Yii::$app->db->createCommand()
->batchInsert($firstModel->tableName(), $columnsToInsert, $rowsToInsert)
->execute();
$isSuccess = ($numberAffectedRows === count($models));
if($isSuccess){
$changedAttributes = array_fill_keys($columnsToInsert, null);
foreach($modelsToInsert as $model){
$model->afterSave(true, $changedAttributes);
}
}
return $isSuccess;
} else {
return true;
}
}
}
This class can be used:
use common\components\Model;
/**
* #var SomeActiveRecord[] $models Array that contains array of active records (type SomeActiveRecord)
*/
// ...
if (Model::validateMultiple($models)){
if(!Model::saveMultiple($models)){
// ... some error handling
}
} else {
foreach($models as $model){
if($model->hasErrors()){
$errors = $model->getFirtsErrors();
// ... some error handling
}
}
}
Additionally, for more convenient working with multiple models can be developed special Collection class that implements \ArrayAccess and \Iterator interfaces. This collection can iterated as simple array, however it contains special methods for bulk operations. Something like this:
foreach($modelCollection as $model){
// ...
}
$modelCollection->validate(); // works similar to common\components\Model::validateMultiple()
$modelCollection->save(); // works similar to common\components\Model::saveMultiple()
Hello i am having slight trouble with arrays in my application. I have a table in my database called "contacts" inside that table i have a column "info" of datatype 'TEXT' where i store a json encoded array. This is my function:
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$contact = new Contacts;
$contact->type = $request->type;
$contact->name = str_replace(' ', ' ', $request->type == 'person' ? $request->first_name . ' ' . $request->other_name . ' ' . $request->last_name : $request->description);
$contact->email = $request->email;
$contact->info = json_encode($request->info);
if ($contact->save())
{
return [
'success' => 'Data was saved successfully!'
];
}
}
Now this saves perfectly however the issues is when i retrieving the data from the database it returns that column as a "string" and as such i am unable to access that array from my front-end javascript (i use angular).
I have tried decoding the entire returned result but that did not work, still had the same problem:
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$type = Input::get('type');
$contacts = "";
if (empty($type))
{
$contacts = Contacts::get();
}
elseif ($type == 'persons')
{
$contacts = Contacts::where('type', 'person')->get();
}
elseif ($type == 'companies')
{
$contacts = Contacts::where('type', 'company')->get();
}
return [
'contacts' => json_decode($contacts)
];
}
Use the $casts property on your model:
class Contacts extends Eloquent
{
protected $casts = ['inof' => 'json'];
}
It'll handle all encoding/decoding for you.
$contact->info = $request->info;