How to get Sum from relationship in laravel - mysql

//Client Model
protected $fillable = [
'client_name', 'plan_id', 'client_type'
];
public function plan(){
return $this->belongsTo(Plan::class, 'plan_id', 'id');
}
// Plan Model
protected $fillable = [
'price'
];
public function clients()
{
return $this->hasMany(Client::class);
}
I want to get total price of all clients where client_type = something

I would do it like this:
function getClientTypeTotal($clientType)
{
return Client::where('client_type', $clientType)->get()->sum(function ($client) {
return $client->plan->price;
})
}

Related

How to fetch data from a json with laravel

I premise that I'm new to the Laravel environment.
I have this JSON file in the database
{
"48:CE:B8:09:7D:AD": ["-91"],
"70:61:91:66:6B:1E": ["-81", "-69", "-79", "-65", "-74"],
"4B:6F:42:53:EB:82": ["-84", "-73", "-81"],
"77:87:80:27:2B:31": ["-83", "-70", "-82", "-71", "-79", "-71", "-79", "-71", "-80", "-72"],
"43:FD:25:20:5A:7B": ["-76", "-84", "-76", "-88", "-77", "-86"],
"C1:04:08:03:3C:05": ["-73"],
"7F:D2:44:60:82:BD": ["-88", "-79", "-88"],
"FE:47:DA:73:90:29": ["-55", "-43", "-59", "-35", "-46", "-38", "-49"],
"62:46:58:C8:A9:9A": ["-68", "-77", "-68"],
"68:13:E4:00:12:30": ["-68", "-81"],
"4E:0D:D6:41:77:FA": ["-68", "-77", "-68", "-76", "-68", "-79", "-71"],
"71:B0:03:A6:17:A5": ["-82", "-73", "-81", "-73"],
"19:F2:64:21:35:B5": ["-74", "-65", "-77", "-69", "-78", "-69"],
"5C:D5:BA:32:06:AD": ["-86"],
"11:91:3D:57:0E:F0": ["-90", "-82"],
"44:08:E7:5C:56:B3": ["-89", "-80"],
"58:99:6F:53:65:C8": ["-77", "-85"],
"54:3C:61:D8:5B:DD": ["-88", "-79"],
"59:02:8C:78:5D:E1": ["-85", "-73", "-82", "-69", "-84", "-75", "-83", "-71"],
"64:F0:DC:95:6E:16": ["-86", "-78"],
"71:E5:42:BA:19:F4": ["-91", "-77", "-86", "-73", "-84", "-74", "-84"],
"E1:63:14:57:89:25": ["-48", "-57", "-38", "-47"],
"57:7D:E9:6F:06:24": ["-85"],
"56:B2:4B:5B:7E:2E": ["-88", "-80"],
"64:3D:02:D4:ED:4E": ["-76", "-64", "-72"],
"0C:93:8F:E5:C6:2A": ["-76", "-66"],
"3F:47:42:77:BD:9A": ["-64", "-83"],
"3C:46:5E:20:9A:FE": ["-79", "-57", "-74"],
"67:58:EE:A8:9D:CC": ["-64", "-80"],
"C4:A5:DF:24:05:7E": ["-65"],
"79:B8:3B:90:31:12": ["-89", "-71", "-88", "-75"],
"75:8E:FE:9B:69:DA": ["-93"],
"49:BE:B0:74:7A:71": ["-66", "-82"],
"55:33:20:52:E1:EC": ["-75"],
"45:D3:80:F3:A4:59": ["-79", "-71"],
"44:CA:8A:EF:31:45": ["-92", "-78"],
"5F:0D:99:F8:EE:94": ["-83"]
}
and I would like to get only some MAC addresses and respective RSSI values using Laravel.
My Model is the following:
class DataFromRasp extends Model
{
use HasFactory;
public $timestamps = false;
protected $primaryKey = 'id';
protected $fillable = ['device'];
protected $casts = ['device' => 'array'];
}
And my controller:
class DataFromRaspController extends Controller
{
public function index()
{
$data=DataFromRasp::all();
return view('backend.auth.user.dictionary', compact("data"));
}
public function create()
{
}
public function store(Request $request)
{
}
public function show(DataFromRasp $dataFromRasp)
{
}
public function edit(DataFromRasp $dataFromRasp)
{
//
}
public function update(Request $request, DataFromRasp $dataFromRasp)
{
//
}
public function destroy(DataFromRasp $dataFromRasp)
{
//
}
public function getDict(Request $request)
{
$data = $request->get('jsondata');
$data = json_decode($data, true);
DataFromRasp::create(['device' => $data]);
return back()->with('success', 'Data successfully store in json format.');
}
}
The getDict() function receives the JSON from a raspberry and saves it in the DB.
The structure of the DB table is as in figure
https://imgur.com/a/pwsaIeM
I need the values of the MAC addresses "E1:63:14:57:89:25" and "FE:47:DA:73:90:29", how can I get them?

Laravel 5.8 show data of the another table like join

I need how to show data in another table like MySQL join or something like that
MySQL example
My Code
Model usuarios
class Usuario extends Model {
protected $table = 'usuarios';
protected $primaryKey = 'idusuarios';
protected $filliable = [
'cedula', 'nombre', 'tele1', 'tele2', 'correo', 'direccion',
'user_name', 'user_pass', 'fecha_ingreso', 'usu_idrol'
];
public function Usuario() {
return $this->hasOne('app\Roles','idrole','usu_idrol','desc_rol');
}
const CREATED_AT = NULL;
const UPDATED_AT = NULL;
}
Model Roles
class Roles extends Model {
protected $table ='roles';
protected $primarykey = 'idrole';
protected $filliable = ['desc_rol'];
public function Roles() {
return $this->belongsTo('app\Usuario', 'usu_idrol', 'idrole');
}
}
Controller usuarios
public function index(Request $request) {
if (!$request->ajax()) return redirect('/');
$usuarios = Usuario::all();
return $usuarios;
}
View usuarios
that's what I need
Try this in the controller that is returning data to your vue instance
//get all the users from the database (in your controller)
//you need to create a new array so as to easily map the role in the returned results
return Usuario::with('Usuario')->get()->map(function($role) {
return [
'field1' => $role->field1,
'field2' => $role->field2,
'field3' => $role->field3,
'field4' => $role->field4,
'field5' => $role->field5,
'rol' => $role->Usuario->desc_role
];
});

How to passing parameter to afterSave() Method in yii2?

I'm new to yii2. I want to write afterSave() method after insert new record. My scenario is: when the user add a damage must be send email to him.
When user add damage, does not enter the serial number. I should read his name and serial damage but I don't know how to passing serial from Controller to model.
Damage Model:
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
$name = $this->user->name;
$serial = ?
$to = $this->user->email;
$subject = 'new damage';
$body = 'mr'.$name.'your damage with serial number'.$serial.'is registered';
if ($insert) {
App::sendMail($to, $subject, $body);
}
}
DamageController:
public function actionAddDamage($serial){
$model = new Damage();
$gaurantee = Gaurantee::find()->where(['serial' => $serial])->andWhere(['user_id' => Yii::$app->user->id])->one();
if (!$gaurantee)
throw new ForbiddenHttpException('You don't access');
$model->gr_id = $gaurantee->id;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('addDamage',
['model' => $model,
'servers' => $servers,
'gaurantee' => $gaurantee,
]);
}
public function init(){
$this->on(self::EVENT_AFTER_INSERT, [$this, 'sendMail']);
}
public function sendMail($event) {
}
First that comes to mind is to add attribute in damage model.
//Damage model
public $serial;
Then in your controller you can set value for this:
public function actionAddDamage($serial){
$model = new Damage();
$gaurantee = Gaurantee::find()->where(['serial' => $serial])->andWhere(['user_id' => Yii::$app->user->id])->one();
if (!$gaurantee)
throw new ForbiddenHttpException("you don't access");
$model->serial = $serial;
.....
In your afterSave() method you will have your serial as $this->serial.
2nd way is to get it from guaranty table since you have $this->gr_id , but this will generate 1 more db request.
You can create a property $serial in your Damage Model and assign the serial value to the $model->serial property in your Controller. For Example:
class Damage extends yii\db\ActiveRecord
{
public $serial = null;
public function afterSave($insert, $changeAttributes) {
// ...
var_dump($this->serial);
}
}
And in the controller you can assign $serial to the model:
public function actionAddDamage($serial) {
$model = new Damage();
$model->serial = $serial;
// ...
}

professional way add data in database laravel 5.2

what is the professional way insert record in database.
i am using laravel 5.2.
i'm new in laravel.
class students extends Controller
{
public function index()
{
$insertData = array(
"name" => Input::get("name"),
"detail" => Input::get("detail"),
"token_key" => Input::get("_token")
);
return view('student');
}
public function fees()
{
$record = array(
"p_name" => Input::get("name"),
"p_fees" => Input::get("fees"),
"p_detail" => Input::get("detail")
);
return view('fee');
}
}
stander able way?
You should use mass assignment. Fill $fillable array inside your model and use this:
Model::create($insertData);
public function store_student(Request $request)
{
$student = new Student;
$student->name = $request->name;
$student->detail = $request->details
$student->save();
return view('student');
}
public function store_fee(Request $request)
{
$fee = new Fee;
$fee->p_name = $request->name;
$fee->p_fee = $request->fees;
$fee->p_detail = $request->details
$fee->save();
return view('fee');
}
I suggest you to read this from Laravel official guide.
However you can do it like this:
DB::table('tablename')->insert($insertData);

Yii2, Model find() with custom attribute

I want to pull the model data with custom attribute that assigned in a function in model.
Example)
class Test extends ActiveRecord
{
public static function tableName()
{
return '{{%test}}';
}
public function rules()
{
//....
}
public function attributeLabels()
{
return [
'id' => 'ID',
'first_name' => 'First Name',
'last_name' => 'Last Name',
];
}
public function getFullName()
{
$fullName = $this->first_name.' '.$this->last_name;
return $fullName;
}
}
Test::find().with('fullName') => it doesn't work
How can I get all the data with fullname attribute?
with is for relations. You can get fullname attribute just by calling $model->fullName. Actually fullName is not an attribute, yii2 utilise php's magic method __get() to get it from getFullName() method.
Example:
$model = Test::findOne($id);
echo $model->fullName;
Example 2:
$models = Test::find()->all();
foreach($models as $model)
{
echo $model->fullName;
}
Also consider using of fields/extraFields methods if you want use your models as arrays instead of objects