laravel eloquent get table 1 based on search of table 2 -


fixed

so after many responses question got real question thought out , answered still leaves me wondering why eloquent can't handle issue of

a->b->c

given object of accessing b items based on value within c (name=script)

the below solution works , because laravel has scopes keeps things clean feel there should easier , faster solution.

public function scopetype($query, $type)     {          return $query->join('article_image_types', 'article_image_types.id', '=', 'article_images.article_image_type_id')->where('name', $type);     } 

if have 2 tables image , image_type , want find images specific type in eloquent?

say have type of "script" id "1" know can do, image collection

where('image_type_id', '1') 

but how below worked

where('name', 'script')

goal:

i want able access data blade file below using scope

<input type="text" name="['image']['script']" value="{!! $article->articleimage()->type('script') !!}"> 

or better accessing images based on type through form model binding ['image']['script']

so works

foreach($article->articleimages->all() $item) {             dd($item->articleimagetype->name);         } 

and return "script"

but how 1 says "script"

::update::

so setup scope expected problem trying based on secondary tables name

$query->where('name', $type); 

your solution work if wanted do

$query->where('image_type_id', 1); 

sqlstate[42s22]: column not found: 1054 unknown column 'name' in 'where clause' (sql: select * article_images article_images.article_id = 32 , article_images.article_id not null , name = script)

update

so doing below produces want except don't type name , can't seem has('articleimagetype') or has('articleimages.articleimagetype')

$article->articleimages()->wherehas('articleimagetype', function($query){             $query->where('name', 'script');         })->has('articleimagetype')->get(); 

just use join:

\db::table('image')    ->join('image_type','image_type.id','=', 'image.image_type_id')    ->where('image_type.name','=','script')    ->get(); 

edit:

after goal update, see want. laravel has feature named query scope let find data way trying to.

in articleimage model, create scope:

public function scopetype($query, $type) {     return $query->join('article_image_type','article_image_type.id','article_image.type_id')                  ->where('type', $type); } 

then can $article->articleimage()->type('script').