I want to make a filter with different parameters. One of parameter is $article_title. But it can be empty . My problem is even if its not empty i get null in return $comments. That is because this part of code:
$q->where('language_id', $default_language_id)->where('title','like',$article_title);
This is my function
public function getResultCommentsWithArticle($comment,$user_firstname,$article_title,$orderBy){
$default_language = Languages::where('default',1)->first();
$default_language_id = $default_language->id;
$comments = ArticleComments::orderBy($orderBy,'desc')
->with(['user', 'article', 'article.translations' => function($q) use($default_language_id,$article_title) {
$q->where('language_id', $default_language_id)->where('title','like',$article_title);
}])->paginate(10);
return $comments;
}
EDIT:
I also tried like this:
$comments = ArticleComments::orderBy($orderBy,'desc')
->with(['user', 'article', 'article.translations' => function($q) use($default_language_id,$article_title) {
$q->where([
['language_id', '=', $default_language_id],
['title', 'like', '%'. $article_title .'%'],
]);
}])->paginate(10);
But i get all comments and not comments with title="something"
$comments = ArticleComments::orderBy($orderBy,'desc')
->with(['user', 'article'])
->whereHas('article.translations', function($q)
use($default_language_id,$article_title) {
$q->where('language_id', $default_language_id)
->where('title','like',$article_title);
})->paginate(10);
Try this:
$comments = ArticleComments::orderBy($orderBy, 'desc')
->with(['user', 'article' => function ($q) use($default_language_id, $article_title) {
$q->with('translations')
->whereHas('translations', function ($q) use($default_language_id, $article_title) {
$q->where('language_id', $default_language_id)->where('title','like',$article_title);
});
}])->paginate();
This will select all comments and it will attach to it articles that match the translation.title and default language id.
In case you want to filter the comments instead of articles you would do this:
$comments = ArticleComments::orderBy($orderBy, 'desc')
->with(['user', 'article.translation'])
->whereHas('article', function ($q) use($default_language_id, $article_title) {
$q->whereHas('translations', function ($q) use($default_language_id, $article_title) {
$q->where('language_id', $default_language_id)->where('title','like',$article_title);
});
})->paginate();
return $comments;
Related
Im trying to figure out why my query is ignoring everything except the title and the description. The search button leading to the controller, is for filtering different type of ads , by category, by region, by price.
For example if now i search for existing ad and its found by title / keyword -> will always show, even if i choose a different region / category/ price range
Im trying to use something that will save me a lot of if statements to check if they exist in the request. Maybe other option si to use https://github.com/mohammad-fouladgar/eloquent-builder to build my query
public function index(Request $request)
{
$keyword = $request['keyword'];
$category_id = $request['category_id'];
$type_id = $request['type_id'];
$region_id = $request['region_id'];
$min_price = $request['min_price'];
$max_price = $request['max_price'];
$result = Ad::when($keyword, function ($q) use ($keyword) {
return $q->where('title', 'like', '%' . $keyword . '%')->orWhere('description', 'like', '%' . $keyword . '%');
})
->when($category_id, function ($q) use ($category_id) {
return $q->where('category_id', $category_id);
})
->when($region_id, function ($q) use ($region_id) {
return $q->where('region_id', '=', $region_id);
})
->when($type_id, function ($q) use ($type_id) {
return $q->where('adtype_id', '=', $type_id);
})
->when($min_price, function ($q) use ($min_price) {
return $q->where('price', '>=', $min_price);
})
->when($max_price, function ($q) use ($max_price) {
return $q->where('price', '<=', $max_price);
})
->paginate(8);
My get param url looks like that:
search?keyword=&category_id=0®ion_id=0&type_id=0&min_price=&max_price=
The produced query in mysql when i search for existing ad by its name and i look for a different category is:
select * from `ads` where `title` like '%test test%' or `description` like '%test test%' and `category_id` = '2' limit 8 offset 0
The ad is found, but the actual category is 1, not 2, same for all others optimal parameters.
You can edit your query to look for specific relations, using whereHas. This method will allow you to add customized constraints to a relationship constraint, such as checking the content of a comment.And to check max/min price, use where method. So, you can use it like this:
$result = Ad::when($keyword, function ($q) use ($keyword) {
return $q->where('title', 'like', '%' . $keyword . '%')->orWhere('description', 'like', '%' . $keyword . '%');
})
->whereHas('category_relation_name', function ($q) use ($category_id) {
return $q->where('category_id', $category_id);
})
->whereHas('region_relation_name', function ($q) use ($region_id) {
return $q->where('region_id', $region_id);
})
->whereHas('type_relation_name', function ($q) use ($type_id) {
return $q->where('adtype_id', $type_id);
})
->where('price', '>=', $min_price);
->where('price', '<=', $max_price);
->paginate(8);
My code here is working fine but I need it to be short. I'm using if statement so Select if I will use user_id or Guest_ip.
But I get a long code, any help?
if (Auth::guest()) {
$Task = Enrollee::with('path.ProgrammingField')->with(['path.pathtags' => function ($q) use ($TagArray)
{
$q->with(['Tasks' => function ($q) use ($TagArray)
{$q->has('tasktags', '=', 2)->orderBy('id', 'ASC') ->whereDoesntHave('tasktags',
function ($query) use ($TagArray) {
$query->whereNotIn('name', $TagArray);
}
)
->with('tasktags');
}]
)->orderBy('id', 'ASC');
}])
->where( 'user_id' , '=' , Auth::user()->id )
->where('Path_id', $Path->id) ->get();
$Tasks = $Task[0]->path;
$Subs = Enrollee::where( 'user_id' , '=' , Auth::user()->id )->where('Path_id', $Path->id)->get();
$AllSubs = [];
foreach($Subs as $sub){
$AllSubs[] = $sub->task_id;
}
$AllSubTasks = implode(" ",$AllSubs);
$SubTasks = explode(",", ($AllSubTasks));
}
else {
$Task = Enrollee::
with('path.ProgrammingField')
->with(['path.pathtags' => function ($q) use ($TagArray)
{
$q->with(['Tasks' => function ($q) use ($TagArray)
{$q->has('tasktags', '=', 2)->orderBy('id', 'ASC')
->whereDoesntHave('tasktags',
function ($query) use ($TagArray) {
$query->whereNotIn('name', $TagArray);
}
)
->with('tasktags');
}]
)->orderBy('id', 'ASC');
}])
->where( 'guest_ip' , '=' , '127.0.0.1' )
->where('Path_id', $Path->id) ->get();
$Tasks = $Task[0]->path;
$Subs = Enrollee::where( 'guest_ip' , '=' ,'127.0.0.1') ->where('Path_id', $Path->id)->get();
$AllSubs = [];
foreach($Subs as $sub){
$AllSubs[] = $sub->task_id;
}
$AllSubTasks = implode(" ",$AllSubs);
$SubTasks = explode(",", ($AllSubTasks));
}
Can I Use
if (Auth::guest()) {
->where( 'guest_ip' , '=' , '127.0.0.1' )
}
I need to be one code and change if I use guest_ip or user id Using if statement
Hope this will help you.
$ObjTask = Enrollee::with('path.ProgrammingField')
->with(['path.pathtags' => function ($q) use ($TagArray) {
$q->with(['Tasks' => function ($q) use ($TagArray) {
$q->has('tasktags', '=', 2)->orderBy('id', 'ASC')
->whereDoesntHave('tasktags', function ($query) use ($TagArray) {
$query->whereNotIn('name', $TagArray);
}
)
->with('tasktags');
}]
)->orderBy('id', 'ASC');
}])
->where('Path_id', $Path->id);
$Subs = null;
if (Auth::guest()) {
$Task = $ObjTask->where('user_id', '=', Auth::user()->id)->get();
$Subs = Enrollee::where('user_id', '=', Auth::user()->id)->where('Path_id', $Path->id)->get();
}
else {
$Task = $ObjTask->where('guest_ip', '=', '127.0.0.1')->get();
$Subs = Enrollee::where('guest_ip', '=', '127.0.0.1')->where('Path_id', $Path->id)->get();
}
$Tasks = $Task[0]->path ?? null;
$AllSubs = [];
$AllSubTasks = $SubTasks = null;
if (!empty($Subs)) {
foreach ($Subs as $sub) {
$AllSubs[] = $sub->task_id;
}
$AllSubTasks = implode(" ", $AllSubs);
$SubTasks = explode(",", ($AllSubTasks));
}
After properly indenting the code (like #castis correctly advised) , you can start extracting the bits within the statements into methods. That's called refactoring.
From wikipedia:
Code refactoring is the process of restructuring existing computer code—changing the factoring—without changing its external behavior.
It will look something like this:
if(true) {
doWhateverNeedsToBeDone();
} else {
doTheOtherThing();
}
And you copy all code and paste into the body of these new methods.
user has relation with creater one to one but creater has relation with archive belongsToMany
$creatorQuery = User::query();
$cultivator_id = 2;
$creatorQuery = $creatorQuery->select('id', 'name', 'email', 'role');
$creatorQuery = $creatorQuery->with('creater', function($q) {
$q->whereHas('archive', function($q) use($cultivator_id) {
$query->where('caltivater_id', $cultivator_id);
});
});
$creators = $creatorQuery->get();
showing error mb_strpos() expects parameter 1 to be string, object given
function is supposed to be passed into creater, so you need to change your call to be a key/value array:
$creatorQuery = $creatorQuery->with(['creater' => function($q) use($cultivator_id) {
$q->whereHas('archive', function($q) use($cultivator_id) {
$query->where('caltivater_id', $cultivator_id);
});
}]);
You've said you want to get users by their caltivater_id value defined in Archive model. Use nested whereHas():
$creators = User::whereHas('creator', function($q) use($cultivator_id) {
$q->whereHas('archive', function($q) use($cultivator_id) {
$q->where('caltivater_id', $cultivator_id);
});
})
->with('creators')
->get();
Or use dot notation:
$creators = User::whereHas('creator.archive', function($q) use($cultivator_id) {
$q->where('caltivater_id', $cultivator_id);
})
->with('creators')
->get();
I have built a multi filter search for my website but I cant seem to find any documentation on multiple if statements inside of where for my search.
Returns Lots of Results
$data = Scrapper::paginate(15);
Returns none.. need it to be this way to have where statements with IF see bellow.
$database = new Scrapper;
$database->get();
Example of what I want to do..
$database = new Scrapper;
if (isset($_GET['cat-id'])) {
$database->where('cat_id', '=', $_GET['cat-id']);
}
if (isset($_GET['band'])) {
$database->where('price', 'BETWEEN', $high, 'AND', $low);
}
if (isset($_GET['search'])) {
$database->where('title', 'LIKE', '%'.$search.'%');
}
$database->get();
Very similar to this: Method Chaining based on condition
You are not storing each query chains.
$query = Scrapper::query();
if (Input::has('cat-id')) {
$query = $query->where('cat_id', '=', Input::get('cat-id'));
}
if (Input::has('band')) {
$query = $query->whereBetween('price', [$high, $low]);
}
if (Input::has('search')) {
$query = $query->where('title', 'LIKE', '%' . Input::get($search) .'%');
}
// Get the results
// After this call, it is now an Eloquent model
$scrapper = $query->get();
var_dump($scrapper);
Old question but new logic :)
You can use Eloquent when() conditional method:
Scrapper::query()
->when(Input::has('cat-id'), function ($query) {
$query->where('cat_id', Input::get('cat-id'));
})
->when(Input::has('band'), function ($query) use ($hight, $low) {
$query->whereBetween('price', [$high, $low]);
})
->when(Input::has('search'), function ($query) {
$query->where('title', 'LIKE', '%' . Input::get('search') .'%');
})
->get();
More information at https://laravel.com/docs/5.5/queries#conditional-clauses
I'm trying to make an advanced search form with Laravel 4, and this is the query:
$result = DB::table('users_ads')
->join('ads', 'users_ads.ad_id', '=', 'ads.id')
->orderBy($column, $method)
->where('status', TRUE)
->where(function($query) use ($input)
{
$query->where('short_description', $input['search'])
->where('category', $input['category'])
->where('product', $input['product']);
})
->join('users', 'users_ads.user_id', '=', 'users.id')
->select('ads.id', 'ads.img1', 'ads.short_description', 'ads.category', 'ads.product', 'ads.price', 'users.city')
->get();
return $result;
The problem is that the user might not use all the input fields. So i want to include some if conditions in this part:
$query->where('short_description', $input['search'])
->where('category', $input['category'])
->where('product', $input['product']);
.. so if the input is empty, to remove the "where" condition.
You could wrap each where in an if statement.
$query = DB::table('user_ads')
->join('ads', 'users_ads.ad_id', '=', 'ads.id')
->orderBy($column, $method);
if ($input['search']) {
$query->where('short_description', $input['search']);
}
if ($input['category']) {
$query->where('category', $input['category']);
}
$query->join('users', 'users_ads.user_id', '=', 'users.id')
->select('ads.id', 'ads.img1', 'ads.short_description', 'ads.category', 'ads.product', 'ads.price', 'users.city')
$result= $query->get();
return $result;
Something along those lines would work I believe.
$filters = [
'short_description' => 'search',
'category' => 'category',
'product' => 'product',
];
.....
->where(function($query) use ($input, $filters)
{
foreach ( $filters as $column => $key )
{
$value = array_get($input, $key);
if ( ! is_null($value)) $query->where($column, $value);
}
});
Newer version of Laravel have a when method that makes this much easier:
->where(function ($query) use ($input, $filters) {
foreach ($filters as $column => $key) {
$query->when(array_get($input, $key), function ($query, $value) use ($column) {
$query->where($column, $value);
});
}
});
$role = $request->input('role');
$users = DB::table('users')
->when($role, function ($query) use ($role) {
return $query->where('role_id', $role);
})
->get();