I have two related models in a job listing application, Company and Listing. The relationship between them is that company may have listing and a listing must have exactly one company.
class Company extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'description',
'email',
'website',
'logo',
'address',
'city',
'state',
];
//Relationship to Listing
public function listings(){
return $this->hasMany(Listing::class, 'company_id');
}
//Relationship to company_image
public function company_image(){
return $this->hasMany(CompanyImage::class, 'company_id');
}
//Relationship to User
public function user(){
return $this->belongsTo(User::class, 'user_id');
}
}
The listing model is defined as
class Listing extends Model
{
use HasFactory;
//Relationship to User
public function user(){
return $this->belongsTo(User::class, 'user_id');
}
//Relationship to Company
public function company(){
return $this->belongsTo(Company::class, 'company_id');
}
I tried
public function edit(Listing $listing)
{
$cid = $listing->only(['id']); //to get the id of the company from the listings table
$cid = $cid['id'];
$comp = Company::orderby('name','Asc')->get(); // this list all company in a select field
$company = Company::whereHas('listings', function ($query) { //to get record of the company using the $cid from the listings table
$query->where('listings.id','=',$cid);
})->get();
dd($company); //to check the value returned.
// return view('listings.edit',[
// 'listing' => $listing,
// 'company' => $company,
// 'companys' => $comp
// ]);
}
i get an Undefined variable $cid when i use it like so where('listings.id','=',$cid). i get null when i use it like so where('listings.id','=','$cid').
I want to get a result like
SELECT companies.name, companies.logo FROM companies join listings on listings.company_id = companies.id where listings.id = 4
which looks like: enter image description here
You get the error because you need to pass the variable to closure.
You can pass the variable using use($variable)
after function()
$company = Company::whereHas('listings', function ($query) use ($cid){
$query->where('listings.id','=',$cid);
})->get();