laravel 5.2 search in related entity - php

Suppose I have a Model called 'Commodity' which has category_id belongs to a category.
In Commodity.php I defined this relationship:
public function category(){
return $this->belongsTo('App\Category');
}
Now, I want to find the commodities which their category name include 'glass'
I tried this:
$items = Commodity::orderBy('id', 'desc')->category()->where('title', 'LIKE', '%glass%');
But it populates this error:
Call to undefined method Illuminate\Database\Query\Builder::category()

Please read official documentation that covers querying relations.
Sometimes you may wish to eager load a relationship, but also specify additional query constraints for the eager loading query. Here's an example:
$users = App\User::with(['posts' => function ($query) {
$query->where('title', 'like', '%first%');
}])->get();
So, regarding your question I'd suggest to try next:
$commodities = App\Commodity::with(['category' => function ($query) {
$query->where('title', 'like', '%glass%');
}])->orderBy('id', 'desc')->get();

Related

How to get data from foreign key in laravel 5.1?

I am using laravel 5.1 for my new project smart search.
My problem is to get data from foreign key using like query for search of that table.
My database tables are:
category->id, name
search->id, category_id (foreign_key), question, answer, tags
My model code is:
category model
public function helpcenter() {
return $this->belongsTo('App\HelpCenter');
}
helpcenter model
public function category() {
return $this->hasOne('App\HelpCenterCategory', 'id', 'category_id');
}
My controller function for search query is
$queries = HelpCenter::has('category')
->where('questions', 'LIKE', '%'.$term.'%')
->orwhere('category_id.name','LIKE','%'.$term.'%')
->take(5)->get();
You will want to use whereHas() to subquery a relationship:
$queries = HelpCenter::whereHas('category', function($category) use ($term)
{
$category->where('name','LIKE','%'.$term.'%');
})
->orWhere('questions', 'LIKE', '%'.$term.'%')
->take(5)->get();
whereHas() is documented here: http://laravel.com/docs/5.1/eloquent-relationships#querying-relations

Laravel search 'LIKE' query in two tables

I'm currently trying to set up a search bar that filters the results of two tables, books and categories.
I have setup relationships for both models where:
Book.php (Model) (table: id, b_name, b_author, cat_id)
public function bookCategory()
{
return $this->belongsTo('Category', 'cat_id', 'id');
}
Category.php (Model) (table: id, cat_name)
public function book()
{
return $this->hasMany('Book', 'cat_id', 'id');
}
BookController.php
public function getFilterBooks($input)
{
$books = Book::with('bookCategory')->where('**cat_name at category table**. 'LIKE', '%' . $input . '%'')->get();
return Response::json($books);
}
But obviously this won't work. The reason I'm doing this is because I want to allow users to use the same search bar to filter different columns (which I know how to do it in one table, but not two or more).
You can use that.
Book::whereHas('bookCategory', function($q) use ($input)
{
$q->where('cat_name', 'like', '%'.$input.'%');
})->get();
See more in http://laravel.com/docs/4.2/eloquent#querying-relations
EDIT:
Book::with('bookCategory')->whereHas('bookCategory', function($q) use ($input)
{
$q->where('cat_name', 'like', '%'.$input.'%');
})->get();
You get cat_name from relation.

Laravel 5 Model::with() behavior

I'm trying to get a simple list of products with a given category, using Laravel 5's (L5) Model::with() method. But it seems that L5 ignores the category where clause.
The relation in my Product model:
public function categories(){
return $this->belongsToMany('App\Category', 'categories_products');
}
In my Controller:
public function getByCategory($slug){
$return = Product::with(array('categories' => function($query) use ($slug){
$query->where('slug', 'like', $slug);
}))->paginate(60);
dd($return);
}
The result is a list of every product in my database, instead of just a list of those with the given category slug.
I'v tried to hardcode in some different where clauses, but all seems to be ignored. Am I missing something?
Eloquent doesn't use joins to query related data when using with(), but instead uses separate queries. In your example, it first fetches products and then fetches related categories.
You need to use has() or whereHas() to return only those products that have categories (slugs?).
public function getByCategory($slug){
$return = Product::has('categories')->with(array('categories' => function($query) use ($slug){
$query->where('slug', 'like', $slug);
}))->paginate(60);
dd($return);
}
Or:
public function getByCategory($slug){
$return = Product::whereHas('categories', function($query) use ($slug){
$query->where('slug', 'like', $slug);
})->paginate(60);
dd($return);
}
whereHas() adds a subquery that counts the number of relations. You should use DB::getQueryLog() to see the SQL that Eloquent produces. Makes it a lot easier to figure out what's going on!
Do you need to have an advanced subquery? If slug is defined as a column in product you can do this:
$return = Product::where('slug', 'like', $slug)->paginate(60);
dd($return);
Or if using the relations your query would look like this:
$return = Product::where('slug', 'like', $slug)->categories->paginate(60);
dd($return);

Eager Load Constraints Filter issue in Laravel

I am unable to filter the contents of groups table with respect to username in users table using Eager Load Constraints
public function username()
{
return $this->belongsTo('User','fk_users_id')->select(['id','username']);
}
I have tried using the code below but it filters only the users data not the groups data
$groups = Groups::with(array('username' => function($query) use ($keyword)
{
$query->where('username', 'like', '%'.$keyword.'%');
}))
->where('status',1)->paginate($paginateValue);
any help is welcome...
Think it should be something like this:
Groups::with('User')->whereHas('User', function($q) use ($key){
$q->where('username', 'like', '%'.$key.'%');
})->where('status', 1)->paginate($pagVal);

Laravel - ORM - call to undefined method

app/models/Model.php:
<?php
class Model extends Eloquent {
public function maker()
{
return $this->belongsTo('Maker', 'maker_id', 'id');
}
}
?>
I want to perform a search. The user enters the name of the model and the search should return the maker of that model (each model belongs to a certain maker). The following piece of code doesn't work:
$result = Model::where('title', 'LIKE', '%test%')->maker()->paginate(10);
It gives me the following error:
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::maker()
Any ideas?
I've solved my own problem.
$result = Model::where('models.title', 'LIKE', $query)
->leftJoin('makers', 'models.maker_id', '=', 'makers.id')
->orWhere('makers.title', 'LIKE', $query)
->groupBy('makers.title')
->paginate(10);
According to your solution:
// $search is the keyword to find
Model::with(['maker' => function ($q) use ($search) {
$q->where('title', 'like', "%{$search}%"); // where on makers table
}])->where('title', 'like', "%{$search}%") // where on models table
->paginate(10);
This will return Models that match where clause, with related Makers, but only those who match the where clause too.
But what you need is probably this (according to your question):
Model::with('maker')->where('title', 'like', "%{$search}%") // where on models table
->paginate(10);
This on the other hand returns the Models that match the where clase, each with related Maker
Note: namespace that Model class so it won't collide with Illuminate\Database\Eloquent\Model (which it extends aliased as Eloquent)

Categories