Specifying where-and in Laravel's query builder - laravel

I have the following code which works:
$name = 'jhon';
$users = DB::table('account')->where('login', '=', $name)->get();
How would I specify the AND parameter so that I can query on multiple conditions?
$login = $request->login;
$password = $request->password;
$users = DB::table('account')->where([
['login', '=', $login],
['password', '=', $password]
])->get();
Doesn't work.
$users = DB::table('account')
->where('login', '=', $login and 'password', '=', $password)->get();
To clarify, I'm looking specifically for a query builder solution, not an Eloquent solution.

Use where method twice:
$users = DB::table('account')
->where('login', '=', $login)
->where('password', '=', $password)
->get();

Related

How to reuse parts of Eloquent builder in Laravel

Is there a way to reuse parts of a query in Laravel? For example if I have two queries which share some arbitrarily long section, can I create a function/variable that can be used in place of that section?
Toy queries:
$a = TableA::join('tableb', 'tablea.bid', '=', tableb.id)
->join('talbec', 'tableb.cid', '=', tablec.id)
->join('tabled', 'tablec.did', '=', tabled.id)
->where('tablea_col', '=', true)->get();
$b = TableA::join('tableb', 'tablea.bid', '=', tableb.id)
->join('talbec', 'tableb.cid', '=', tablec.id)
->join('tabled', 'tablec.did', '=', tabled.id)
->where('tableb_col', '=', true)->get();
I would like something like:
$shared = TableA::join('tableb', 'tablea.bid', '=', tableb.id)
->join('talbec', 'tableb.cid', '=', tablec.id)
->join('tabled', 'tablec.did', '=', tabled.id);
$a = shared->where('tablea_col', '=', true)->get();
$b = shared->where('tableb_col', '=', true)->get();
From Laravel 8+, you can clone it then reuse as you wish:
$shared = TableA::join('tableb', 'tablea.bid', '=', tableb.id)
->join('talbec', 'tableb.cid', '=', tablec.id)
->join('tabled', 'tablec.did', '=', tabled.id);
$a = $shared->clone()->where('tablea_col', '=', true)->get();
$b = shared->clone()->where('tableb_col', '=', true)->get();
before Laravel 8, use
$a = clone $shared;
$b = clone $shared;
$a = $a->where('tablea_col', '=', true)->get();
$b = $b->where('tableb_col', '=', true)->get();
You should be able to use a scope for this:
function scopeWithBCandD($query) {
$query->join('tableb', 'tablea.bid', '=', 'tableb.id')
->join('talbec', 'tableb.cid', '=', 'tablec.id')
->join('tabled', 'tablec.did', '=', 'tabled.id');
}
Which would permit:
TableA::withBCandD()->where('tablea_col', true)->get();
TableA::withBCandD()->where('tableb_col', true)->get();

Laravel 8 - How to use where conditions for relation's column

hello friends can you help me to get the contents of $filter? I want to run where which is where the target column is in the relation array
$filter = $request->get('Biogear');
$data = DetailBarang::with(['barang' => function ($q) use ($filter) {
$q->where('brand', '=', $filter);
}])->get();
return response()->json($data);
you can try this
$filter = $request->get('Biogear');
$data = DetailBarang::with('barang')->whereHas('barang',function (Illuminate\Database\Eloquent\Builder $q) use ($filter) {
$q->where('brand', '=', $filter);
})->get();
return response()->json($data);

Search result with multiple tables relation in Laravel6

I'm trying to make search function with relation.
I could display all result using relation And an another code, simple one table search and get result works fine.
but I can't combine those two.
Could you teach me how to combine multiple tables into search function please?
public function order(Request $request)
{
$data = $request->all();
$products = Product::All();
$products = Product::with('categori')
->join('creators', 'creators.id', '=', 'products.creator_id')
->join('categoris', 'categoris.id', '=', 'products.categori_id')
->join('branches', 'branches.id', '=', 'products.br_id')
->join('users', 'users.id', '=', 'products.user_id')
->join('colors', 'colors.id', '=', 'products.color_id')
->get();
$products = Product::when($data['categori_id'], function ($query, $categori_id) {
return $query->where('categori_id', $categori_id);
})->
when($data['color_id'], function ($query, $color_id) {
return $query->where('color_id', $color_id);
})->get();
//return view('result_fb', compact('images'));
$data = array(
'title' => 'index',
'no' => 1,
'products' => $products,
);
return view('product.result', $data);
}
I am not sure if you need 'categori' relation to be loaded or not as there are few $products without it. For general, you can combine all your $products queries to one as follows:
$products = Product::join('creators', 'creators.id', '=', 'products.creator_id')
->join('categoris', 'categoris.id', '=', 'products.categori_id')
->join('branches', 'branches.id', '=', 'products.br_id')
->join('users', 'users.id', '=', 'products.user_id')
->join('colors', 'colors.id', '=', 'products.color_id')
->when($data['categori_id'], function ($query, $categori_id) use ($data) {
return $query->where('categori_id', $data['categori_id']);
})
->when($data['color_id'], function ($query) use ($data) {
return $query->where('color_id', $data['color_id']);
})->get();
If you want to use eager loading with eloquent rather then join, you can use like
$products = Product::with(['creator','categori','branch','user','color'])
->when($data['categori_id'], function ($query, $categori_id) use ($data) {
return $query->where('categori_id', $data['categori_id']);
})
->when($data['color_id'], function ($query) use ($data) {
return $query->where('color_id', $data['color_id']);
})->get();
But for that you Product model should have relations with same name as follows for categori relation:
class Product extends Model
{
public function categori()
{
return $this->belongsTo(Categori::class,'categori_id','id);
}
}
Same way you have to define for all relation used for product.
Try this:
$products = Product::with('categori')
->join('creators', 'creators.id', '=', 'products.creator_id')
->join('categoris', 'categoris.id', '=', 'products.categori_id')
->join('branches', 'branches.id', '=', 'products.br_id')
->join('users', 'users.id', '=', 'products.user_id')
->join('colors', 'colors.id', '=', 'products.color_id')
->when($data['categori_id'], function ($query, $categori_id) {
return $query->where('categori_id', $categori_id);
})
->when($data['color_id'], function ($query, $color_id) {
return $query->where('color_id', $color_id);
})
->get();

laravel 404 error page , redirect

looking for some help, I'm fetching a survey and questions, from method, when select some survey by id, from a route. But when I delete a survey, and when writing in url like http://localhost/survey_details/27 ( 27 is survey Id , which not exist anymore), I'm getting not some expection or redirection or Page not found info, but getting error where undefined variable $dat. But I need some how to show 404 page not found, or just redirect to other page if id not exist. Can some one help me?
here is my route:
Route::get('survey_draft/{id}', 'SurveyController#editSurveyDraft');
Here is my controller:
public function viewSurvey($id)
{
$object = DB::table('question')
->where('survey_id', '=', $id)
->where('name', '!=', NULL)
->get();
$teamName = DB::table('survey')->where('surveyId', '=', $id)
->join('team', 'survey.teamId', '=', 'team.teamId')
->join('company', 'company.id', '=', 'team.companyID')
->get();
$company = Auth::user()->company;
$data = Survey::where('surveyId', '=', $id)->get();
$teams = Auth::user()->teams;
$checkUserTeam = DB::table('teammembersall')
->where('UserId', '=', Auth::user()->id)
->get();
$members = Survey::where('surveyId', '=', $id)
->join('team', 'team.teamId', '=', 'survey.teamId')
->join('teammembersall', 'teammembersall.TeamId', '=', 'team.TeamId')
->join('users', 'users.id', '=', 'teammembersall.UserId')
->select('users.*')
->whereNotExists(function ($query) use ($id) {
$query->select(DB::raw(1))
->from('answer')
->whereRaw('answer.answerAboutUserId = users.id')
->where('answer.surveyId', '=', $id)
->where('answer.member_id', '=', Auth::user()->id);
})
->get();
$questions = DB::table('answer')->get();
return view('survey_details', ['object' => $object, 'data' => $data, 'teams' => $teams, 'members' => $members, 'questions' => $questions, 'checkUserTeam' => $checkUserTeam, 'teamName' => $teamName, 'company' => $company]);
}
To solve your immediate issue, you could add one of these this after $object ... get() depending on your result. One of them should work.
if(empty($object)){ abort(404); }
or
if(!$object->count()){ abort(404); }
However, your code would be much simpler if you used 2 basic laravel technologies.
ORM instead of DB::...
Route model binding. (which would handle your 404 for you)
https://laravel.com/docs/5.6/eloquent
https://laravel.com/docs/5.6/routing#route-model-binding

Laravel eloquent Query Reuse extra condition

I have a query which gives me list of total counts of different items, as:
$data = DB::table($Table1)
->join($table2,$Table1.'.id','=',$Table2.'.device_key')
->where($Table1.'.created_at', '>', $value)
->select('item', DB::raw('count(*) as total'))
->groupBy('item')
->lists('total', 'item');
now i want to fetch same data with extra condition as >where($Table1.'.status', '=', 'SUCCESS') .
how do i do that ??
I don't think you'll get away with anything nice than this.
$query = DB::table($Table1)
->join($table2,$Table1.'.id','=',$Table2.'.device_key')
->where($Table1.'.created_at', '>', $value)
->select('item', DB::raw('count(*) as total'))
->groupBy('item');
$data1 = $query->lists('total', 'rem');
$data2 = $query->where($Table1 . '.status', '=', 'SUCCESS')->lists('total, 'rem');
Use clone to copy the query object for modifications.
$query = DB::table()->where();
$clonedQuery = clone $query;
$clonedQuery->where(..);

Resources