Can you post a whole code and not just a pseudo code?
Jan 8, 2021
19
Level 13
Modify query within a variable
How can i modify a variable when it have query builder ? i mean:
$post = Post::where('id', 1);
if(myCondition){
$post->first();
}
if(anotherCondition){
$post->where('body', 'example');
}
dd($post);
$post always return query builder instance, How can i avoid this :
$post = Post::where('id', 1);
if(myCondition){
$post = $post->first();
}
if(anotherCondition){
$post = $post->where('body', 'example')->first();
}
dd($post);
How to avoid re-assing variable to itself ?
More info https://laracasts.com/discuss/channels/laravel/modify-query-within-a-variable?page=1#reply=679127
Level 24
not really use
$post = $post->where('id', 1);
just
$query = Post::query();
if (condition) {
$query->where('id', 1);
}
if (condition) {
$query->where('id', 2);
}
$posts = $query->get();
and also can use when()
1 like
Please or to participate in this conversation.