Laravel Eloquent relationship data retrieve - laravel

I have below code to get data from database,
$profile = Profiles::find(1);
$currency = Profiles::find($profile->currency_id)->currency;
Then created a relationship in the model as below,
class Profiles extends Model
{
use HasFactory;
protected $table = 'Profiles';
protected $primaryKey = 'profile_id';
public function Currency()
{
return $this->belongsTo(Currencies::class, 'currency_id');
}
}
class Currencies extends Model
{
use HasFactory;
protected $table = 'Currencies';
protected $primaryKey = 'currency_id';
public function profile()
{
return $this->hasOne(Profiles::class, 'currency_id');
}
}
Problem is that there is only 1 profile and 100 currency, currency_id is a foreign key in Profiles table,
I could not get data and get this error, Trying to get property 'currency' of non-object"
If i use $currency = Profiles::find(1)->currency; then it retrieve first row of Curriencies table which is not required data.
How can I get currency row for that specific profile?

The problem is that the find() method will look for the primaryKey and in your second call the currency_id is not the pk.
Two solution for you:
replace the find by a where clause like so: $currency = Profiles::where('currency_id',$profile->currency_id)->value('currency')
Or a more Laravel way to do it, through the relationship $currency = $profile->currency;

Related

Eloquent relationship mass assignment $guarded ignored

I have three table in DB, and I have used belongsTo for merging them. My Admins model looks like this :
class Admin extends Authenticatable
{
use HasFactory;
protected $guarded = ['status', 'shop_name', 'vendor_id', 'id'];
protected $guard = 'admin';
public function getVendorDetails(){
return $this->belongsTo(Vendor::class, 'vendor_id','vendor_id');
}
public function getVendorBusinessDetails(){
return $this->belongsTo(VendorBusinessDetails::class, 'vendor_id','vendor_id');
}
}
I need to prevent shop-name field to be saved through form. this field is in the table name : vendor_business_detals (getVendorBusinessDetails).But in this case $guarded only works for Admins table and ignores another relationship tables and fields of them such as shop_name. In short I am struggling to find the way to add $guarded data for VendorBusinessDetails. My controller looks like below:
$business_data = $request->only(['shop_name', 'shop_address', 'shop_phone']);
//dd($business_data);
$myModel = Admin::find($id);
//business table update
$myModel->getVendorBusinessDetails()->update($business_data);
VendorBusinessDetails model:
class VendorBusinessDetails extends Model
{
use HasFactory;
protected $guarded = ['shop_name'];
protected $table = 'vendors_business_details';
}
I don't know why $guraded=['shop_name'] is ignored. Any help would be highly appreciated.
$myModel->getVendorBusinessDetails()->update($business_data);
If you use "getVendorBusinessDetails" as a method, the model isn't initialize. Only the SQL update command runs.
$myModel->getVendorBusinessDetails->update($business_data);
Using "getVendorBusinessDetails" as a field initializes the model. So, it works as you expected.

Laravel filtering query results with relations

I have this relations
and defined models for all 3 tables
class Employee extends Model
{
use HasFactory;
protected $table = 'employees';
public function departments()
{
return $this->belongsToMany(Department::class, 'dept_emp', 'emp_no', 'dept_no', 'emp_no', 'dept_no');
}
}
class Department extends Model
{
use HasFactory;
protected $table = 'departments';
}
class Dept_emp extends Model
{
use HasFactory;
protected $table = 'dept_emp';
}
And in my controller
$employees = Employee::with('departments')->paginate(50);
I want to filter this query result to be able to select only one chosen department and not all of them.
I tried adding to employee model this function
public function scopeDepartment($query, $department)
{
return $query->where('dept_no',$department);
}
but it isn't working. Can someone advice me how to filter query results with relations?
you can query within with relation as like
$employees = Employee::with(['departments' => function($q) use ($dept_id){
$q->where('dept_no',$dept_id);
}])->paginate(50);
$dept_id is the id of department i.e $dept_id = $request->department_id something like

Getting all values from laravel relationship table

I have below relationship in laravel model for Bills,
protected $table = 'purchase_bills';
protected $primaryKey = 'bill_id';
public function vendors()
{
return $this->belongsTo(Vendors::class);
}
Below relationship for Vendor,
protected $table = 'vendors';
protected $primaryKey = 'vendor_id';
public function bills()
{
return $this->hasMany(Purchasebills::class, 'bill_id');
}
Now i am trying to get all bills of specific vendor with below code,
$bills = Vendors::find(1)->bills()->where('vendor_id', $vendor_id);
return Datatables::of($bills)->make();
But it always returns only 1 row from a table if it is first, even though there are many bills.
How can i get all bills from that vendor_id?
I could resolve the issue, actually, it was a wrong foreign key assignment in the model,
Below is correct one.
return $this->hasMany(Purchasebills::class, 'vendor_id');

Populate laravel object with relationships

I want to populate Every CustomerEvent with the Customer related to the CustomerEvent.
When I Loop through the object and call to $customerevent->customer foreach object I can get the customer related to that event but Can I populate the all objects in the main object without looping through every single event ?
I want to do something like this:
$typeOne = CustomerEvent::typeOne()->get();
$customersWithTypeOne = $typeOne->Customers;
Here my code:
Table 1: "events"
id, customer_id
Model for Table 1 "CustomerEvent":
<?php
class CustomerEvent extends Eloquent{
protected $guarded = ['id'];
public $table = "event";
protected $softDelete = true;
public function scopeTypeOne($query)
{
$followUps = $query->where('type_id', '=', '1');
}
public function Customers()
{
return $this->belongsTo('Customer', 'customer_id');
}
}
Table 2: "customers"
id
Model for Table 2 "Customers":
<?php class Customer extends BaseModel{
protected $guarded = ['id'];
}
EventController:
public function index()
{
$typeOne = CustomerEvent::typeOne()->get();
$customersWithTypeOne = $typeOne->Customers;
dd($customersWithTypeOne);
}
From you database scheme I see customer has many events, so I would recommend to define this relationship in you Customer model.
class Customer extends BaseModel{
protected $guarded = ['id'];
public function events()
{
return $this->hasMany('CustomerEvent', 'customer_id');
}
}
Then you will be able to query customers with events:
$customersWithTypeOne = Customer::whereHas('events', function($query){
$query->where('type_id', 1);
})->get()
Maybe Ardent can help you: https://github.com/laravelbook/ardent
It's an extension for Eloquent models and very popular.

Getting started with laravel (4) models

I'm trying out this model-thing, but I can't really get my grasp of it.
For the moment I have two tables (companies and sellers) "companies" as a column named "cResponsibleID" which I want to map to "sID" in "sellers".
models/Companies.php
class Companies extends Eloquent {
protected $table = 'companies';
protected $primaryKey = 'cID';
public function sellers() {
return $this->belongsTo('Sellers','sID');
}
}
models/Sellers.php
class Sellers extends Eloquent {
protected $table = 'sellers';
protected $primaryKey = 'sID';
public function companies() {
return $this->hasMany('Companies','cResponsibleID');
}
}
I then want to do something like Companies::with('sellers.sName')->get() to "translate" cResponsibleID to sName.
Maybe I'm all out wrong.
Thankful for all help.
Can you try printing the result of:
<?php
$company = Companies::with('sellers')->get();
echo '<pre>';
print_r($company->sellers);
And see how they're build up, I blieve the sellers.ANYTHING construction is only meant for multiple nested relations.
for example of a Seller has an Address as a relation, it would be Companies::with('sellers.address')

Resources