API filtering with pivot table - laravel

I'm using laravel 7 and i've made an API to fetch data with a VUE component.
I want to filter restaurants based on their type of food. So if i query "pizza" i want to show only restaurants that make pizza.
getTypes is a many to many relation.
public function restaurants(Request $request)
{
$ricerca = $request->input('query');
$users = Restaurant::with(array('getTypes' => function ($query) use ($ricerca) {
$query->where('name', "LIKE", "%" . $ricerca . "%");
}))->get();
return response()->json($users);
}
I tried this, but this way i don't have access to other genres, if a restaurant make pizza and meat, i don't see meat anymore.
Any advice?

create a many to many relation with restaurant and pizza.
get an array which restaurant make pize,
$array = [];
or simple var
$array = $request('query');
and put this array in query.
$data = Project::whereHas('restorant_pizza', function ($q) use ($array) {
$q->whereIn('restorant_pizza.pizza_id', $array);
})->get();
I think this idea will help you

Related

Laravel whereHas Returns all records

I have have 3 tables in my projects they are:
products(can have Multiple Variants)
variants (belongsto product)
product_attributes (this have product_id,attribute_id,value_id)
I want to filter variants from a product by value ids thats comes from form request as example (1,2,6)
I have tried like this:
$poruduct_id = $request->product_id;
$value_ids = $request->value_ids;
$searched_variants = Variant::whereHas('product.attributeValues', function ($query) use ($value_ids, $product_id) {
$query->whereIn('value_id', [$value_ids]);
})->where('product_id', $product_id)->get();
dd($searched_variants);
But the problem is the query returns all records from the product. What is the solution to filter exactly the values that the product Variants have?
Thank you.
-UPDATED-
I have tried like this but nothing changed
$searched_variants = Variant::select('product_id')->whereHas('product.attributeValues', function ($query) use ($value_ids, $product_id) {
$query->whereIn('value_id', [$value_ids]);
})->groupBy('product_id')
->havingRaw('COUNT(*) = ?', [count((array) $value_ids)])
->get();
-**FİNALLY SOLUTİON**-
I made it like this : I get the value code that is in for example Large the code is L
get all the codes to controller and executed this query ı hope this helps someone
1.$value_codes=$request->value_codes;
2.$value_codes_array=explode(',',$value_codes);
3.$product_id=$request->product_id;
4.$searchValues = preg_split('/,/', $value_codes_array, -1, PREG_SPLIT_NO_EMPTY);
$searchValues = preg_split('/,/', $value_idss, -1, PREG_SPLIT_NO_EMPTY);
$variants= Variant::where(function ($q) use ($searchValues) {
foreach ($searchValues as $value) {
$q->orWhere('sku', 'like', "%-{$value}")
->orWhere('sku', 'like', "%-{$value}-%")
->orWhere('sku', 'like', "{$value}-%");
}
})->where('product_id',$product_id)->get();
dd($variants);
If you have n variants to one product, you query should be like:
Product Model
public function variants: HasMany relationships
//usage
$produtc->variants->and here the query function
You need to use it in this way, it should work:
$productId = $request->product_id;
$valueIds = $request->value_ids;
$searchedVariants = Variant::whereHas('product.attributeValues', function ($query) use ($valueIds) {
$query->distinct()->whereIn('value_id', $valueIds);
}, '=', count($valueIds))->where('product_id', $productId)->get();

october cms (laravel) where query

I have a some problem with filter query. I need to do somethink like
select painting from artist_painting where type=$_GET['type'] AND material=$_GET['material'] and artist_slug =$_GET['artist_slug'] ORDER BY painting DESC
I have a pivot table artist_painting and artist. 'artist_slug' is in the 'artist' table
I do
$this['painting'] = Painting::whereHas('artist', function($q)
{
$q->where('artist_slug', '=', $this->param('slug'));
})->get();
but I do not know what to do next.
How can i do query in php code?
Short and dirty:
Painting::where('type',input("type"))
->where('material',input("material"))
->whereHas('artist', function($q)
{
$q->where('artist_slug', '=', $this->param('slug'));
})->get();
The explanation:
When you initialize a query a query builder instance is returned. Basically all methods on the query builder return the same instance so you can daisy chain them into one query.
But you can also just work on the query builder.
$query = Painting::where('type',input("type"));
or:
$query = $model->newQuery()// Where model is an intance of painting, for example new Painting();
Then you can just work on the query builder instance, pass it to other methods that might to do things.
function getPaintings($type, $material, $slug)
{
$query = Painting::where('type',$type);
$query->where('material', $material);
$this->findArtistBySlug($query, $slug);
return $query->get()
}
function findArtistBySlug($query, $slug)
{
$query->whereHas('artist', function($q) use ($slug)
{
$q->where('artist_slug', '=', $slug);
});
$query->with(['artist']);
}
You might want to read https://octobercms.com/docs/database/query
and https://laravel.com/docs/5.6/queries
I would solve this problem from the Artist's point of view:
$artist = Artists::where('artist_slug', $this->param('slug'))->with('paintings')->first();
All the paintings of the artist can be accessed by using $artist->paintings, which will be a Collection.

How to get all item same category with Eloquent

Hi all,
I'm building an application in Laravel, I want to get all item in an article category without using this Eloquent.
My code is
$info = Article::find($article_id);
$cate_info = $info->article_categories()->first();
if($cate_info){
$same = Article::with(['article_categories' => function ($query) use ($cate_info){
$query->where('articles_category.ID' ,$cate_info->ID);
}])->where('ID' ,'!=' ,$article_id)->get();
}
And I get all articles. How to solve.
Article and Article_Category is in many to many relationship.
Thanks.
If you want to have all the articles of a particular article_categories you can use whereHas method, now suppose you have name as a field column in categories table, so you can have something like this:
public function getData(Request $request)
{
$category = $request->categoryName;
// $category = 'ABC Category';
$articles = Article::whereHas('article_categories', function($query) use($category) {
$query->where('name', 'like', '%'.$category.'%');
})->get();
return response()->json(['articles' => $articles], 200);
}
Hope this helps.

Laravel 5.4 Relationships Route Binding

I am making an image gallery. Images have a many to many relationship with tags. Images also have a many to many relationship with catagories.
$images = $category->images;
$images = $tag->images;
public function images(Category $category = null)
{
$images = $category->images;
return view('pages.images.index', compact('images'));
}
Route model binding on this code works fine and I can do the same for tags but what I am looking to do is filter on category and then tag.
$images = $tag->category->images;
For example, if I had an image with the tag of "dog" and a category "brown" the query would only return all dogs that are brown.
Can I do this? Both tags and categories could have multiple options so I was hoping for a route like this...
mysite.com/images/{category}/{tag}
Thanks for any help or best direction to go.
You could use the build in laravel whereHas functionality
Image::whereHas('categories', function ($query) use ($category) {
$query->where('NAME', '=', $category);
})->whereHas('tags', function ($query) use ($tag) {
$query->where('NAME', '=', $tag);
})->get();
replace the NAME with the desired field you want to filter on.
You can declare the route just as you stated and then use them as parameters in the controller-method which is connected to the route.
So if you declare a route like Route::get('/register/{token1}/{token2}','RegisterController#confirm');then it is possible to get those wildcards in the method confirm just like normal parameters:
public function confirm(Request $request, $token1, $token2) {}

Laravel eloquent: get data with model wherePivot equal to custom field

I have an eloquent object Performer that has Albums and Albums have Images
Here is setup:
Model Performer->albums():
public function albums()
{
return $this->belongsToMany('Album','performer_albums','performer_id','album_id');
}
Model Album->images()
public function images()
{
return $this->belongsToMany('Image','album_images','album_id','image_id')->withPivot(['type','size']);
}
I have performer object stored as such:
$performer = Performer::where...->first();
Now I need to get Performer's Albums with images where size is 'large'
So to avoid nesting queries, can I use with()?
I tried
$performer->albums()
->with('images')
->wherePivot('size','large')
->get();
But laravel tells me it's trying to use wherePivot for Performer-Album relationship (M-2-M)
PS. I am also aware that I can do this,
$performer = Performer::with('albums')
->with('albums.images')
->.....-conditions for additional fields in album_images....
->get();
but question remains the same.
You need eager load constraints:
$performer->albums()
->with(['images' => function ($q) {
$q->wherePivot('size','large');
}])
->get();
And btw, no, you can't do this:
Performer::with('albums')
->with('albums.images')
->.....-conditions for additional fields in album_images....
->get();
instead you could do:
Performer::with(['albums.images' => function ($q) {
$q-> .....-conditions for additional fields in album_images....
}])->get();

Resources