Laravel get data with belongsto column

Laravel get data with belongsto column



plans table columns
id, name, type



clients table columns
id, name, plan_id


// for client

function plan()
return $this->belongsTo(Plan::class, 'plan_id', 'id');



I input plan_id to Clients table



I want to get those clients data from clients table if plan type ='PP'


$clientData = Client::with(['plan' => function ($clientData)
$clientData->where('type', 'PP');
)->get();



I tried this but I got all data from clients table.




1 Answer
1



->with() doesn't constrain the data from the initial query, it just eager loads it. You need to use ->whereHas() for that:


->with()


->whereHas()


$clientData = Client::with(["plan"])
->whereHas("plan", function ($query)
$query->where("type", "=", "PP");
)->get();



This will only return Client records that have a Plan with a type of PP.


Client


Plan


PP






strpos() expects parameter 1 to be string, array given I got this error.

– ASMSaief
Sep 7 '18 at 17:35






Woops, sorry. ->whereHas() doesn't expect an array; fixed.

– Tim Lewis
Sep 7 '18 at 17:37


->whereHas()






So How can get?

– ASMSaief
Sep 7 '18 at 17:39






@ASMSaief the closure needs to be the 2nd arg to whereHas

– Devon
Sep 7 '18 at 17:41






Thank TimLewis And Devon

– ASMSaief
Sep 7 '18 at 17:42



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)