I am new in Laravel, Having some difficulties to understand the queries
I have 2 tables
Users [id, email, fname , lname ]
Leads [id, other some fields, client, agent]
the client and agent is the foreign key of users table's id..
with the below code i can retrive datas from the Leads table but there i get client = 3 agent = 4 something like this
but instead of showing those ids i want to get the names of those ids from the user table
how to do it?
In the controller i have this function as of now
/**
* @return \Illuminate\Http\Response
*/
public function leads(){
if(Auth::user()->role == 'admin'){
$leads = Leads::all();
// here in the $leads i get datas like ['id' => 1, 'field1' => 'test', 'field2'=> 'test2', 'client_id'=> 2, 'agent_id'=> 3] , but i want to get the names of the client and agent from the user table which we can do in normal sql query by joining but how to do with laravel?
}
return view('leads', compact('leads'));
}
How it can be done ?
in the Users Model & Leads model i have only the default codes i have the code
will appreciate if get some quick help
First you need to change your column names to agent_id
& client_id
instead of agent
& client
. Otherwise you need to update the following code accordingly.
Judging by your answer, i think you need to do something like this in Leads
model:
public function agent()
{
return $this->belongsTo(User::class, 'agent_id');
}
public function client()
{
return $this->belongsTo(User::class, 'client_id');
}
protected $with = ['agent', 'client'];
After you do the above steps, you can simply list an agent/client for a lead by writing:
$lead->agent->name;
$lead->client->name;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.