I need to make a multiple-search on Laravel - php

I want to make a filter who find some things like status of a work order, employee, month (here I must separate month from the rest of date)
Ok I´m working alone on this project so I need some help.
I´ve got relations on my DB like
employee.employee_id inner join main.employee_id_created (I've made it directly on phpmyadmin)
So I want to search by name of employee but it´s on the other table so when I wanna show results it send me an error
public function()
{
if($request)
{
$query = trim($request->get('searchBy'));
}
$searchByName = MaintenanceTasks::select('Employee_Id_created')
->join('employee', 'employee.Employee_Id', '=', 'maintenance_tasks.Employee_Id_created')
->where('Employee_name','like','%'.$query.'%')
->get();
}
blade.php
#foreach($searchByName as $otList)
<td>{{$otList->getTaskId()}}</td>
#foreach($machine as $machineData)
#if($otList->Machine_Id == $machineData->Machine_Id)
#foreach($employee as $employeeData)
#if($machineData->Employee_Id == $employeeData->Employee_Id)
<td>{{$employeeData->getEmployeeName()}}</td>
#endif
#endforeach
#endif
#endforeach //and so on
I would like to make a multiple search using when, but it´s not working

you are just selecting Employee_Id_created so there is no other data than Employee_Id_created in your query result.
Add more columns to select.

create multi search
if (!empty($req1)) {
$serach= $serach->where('col', 'like', '%'.$req1.'%');
}
if (!empty($req2)) {
$serach= $serach->where('col', 'like', '%'.$req2.'%');
}
$serach= $serach->get();
other option
->where([
['col1', 'like', '%'.$req2.'%'],
['col2', 'like', '%'.$req2.'%'],
])

Related

Combine with Relation with where sentence in Laravel8

I'm learning Laravel's relations. I'm having problems with the 2nd line.
I would like to display records that Auth::user table's br_name column = Partner table's br_name column matches.
Could you teach me the right code please?
UPDATE
public function mybr()
{
$blogs = Blog::with('user','category','partner')
->where('App\Partner::partner()->br', Auth::user()->br_name)//I'm having problem this line
->where(function($query){
$query->where('status', '=','new');
->orWhere('status', '=', 'old');
})->paginate(250);
return view('blogs.mybr')->with('blogs',$blogs);
}
You could try the following code, and I have done some query refactoring too.
Like I have used whereIn
$blogs = Blog::with(['user','category','partner' => function ($query) {
$query->where('br', '=', Auth::user()->br_name);
}])->whereIn('status',['new','old'])
->paginate(250);

Trying to related tables columns and sums with Laravel eloquent

Ok.
I have three tables
products
--product_id
--product_name
--product_type_id
--price15
--price23
--description
--bonus_points
--image
productTypes
--product_type_id
--product_type_name
productQuantities
--id
--product_id
--warehouse_id
--quantity
Products are placed in different warehouses so I have to keep tracks of its numbers
And has relationships are like this
class Product extends Model
{
public function productType() {
return $this->belongsTo('App\Models\ProductType','product_type_id','product_type_id');
}
public function productQuantities() {
return $this->hasMany('App\Models\ProductQuantity','product_id','product_id');
}
}
What I want to get is all columns from products and product type name from productType, sum of quantity from productQuantities, so I can perform search on those column values later on with where().
How can I get these columns with Eloquent?
I know I could get them with raw SQL commands but I need to do this way for compatibility reasons.
I tried this way before I ask the question.
But model relations just stopped working with no errors. Values just got emptied out from the other parts of the page.
$products = Product::selectRaw('products.*, productTypes.product_type_name, sum(product_quantities.quantity) as quantitySum')
->leftjoin('productTypes','products.product_type_id','=','productTypes.product_type_id')
->leftjoin('productQuantities','products.product_id','=','productQuantities.product_id')
->where('products.product_id','like','%'.$searchID.'%')
->where('product_name', 'like', '%'.$searchName.'%')
->where('product_type_name', 'like', '%'.$searchType.'%')
->where(function($q) use ($searchPrice) {
$q->where('price15','like','%'.$searchPrice.'%')
->orwhere('price23','like','%'.$searchPrice.'%');
})
->where('points', 'like', '%'.$searchPoints.'%')
->groupBy('products.product_id')
->orderByRaw($query)
->paginate($paginateBy);
Working version before this was simple.
Product::leftjoin('productTypes','products.product_type_id','=','productTypes.product_type_id')
->select('products.*','productTypes.product_type_name')
->where('products.product_id','like','%'.$searchID.'%')
->where('product_name', 'like', '%'.$searchName.'%')
->where('product_type_name', 'like', '%'.$searchType.'%')
->where(function($q) use ($searchPrice) {
$q->where('price15','like','%'.$searchPrice.'%')
->orwhere('price23','like','%'.$searchPrice.'%');
})
->where('points', 'like', '%'.$searchPoints.'%')
->orderByRaw($query)
->paginate($paginateBy);
And I thought any kind of join methods doesn't seem to be working well with Eloquent relationship? But older one has leftjoin method as well.
I have not tested this (and am assuming you want to group on product_type_name but you should be able to do something along the lines of:
$results = Product::with(['productType','productQuantities'])
->select(DB::raw('products.*,
productType.product_type_name,
sum(productQuantities.quantity) as "QuantitySum"'))
->groupBy('productType.product_type_name')
->get();
OR
$results = DB::table('products')
->join('productType', 'productType.product_type_id', '=', 'products.product_type_id')
->join('productQuantities', 'productQuantities.product_id', '=', 'products.product_id')
->select(DB::raw('products.*,
productType.product_type_name,
productType.product_type_name,
sum(productQuantities.quantity) as "QuantitySum"'))
->groupBy('productType.product_type_name')
->get();
Then you should be able to access the aggregated quantities using (in a loop if you wanted) $results->QuantitySum.
you can get it with eager loading and aggregating. For example, you need to query products has product type name like "new product" and quantity greater than 1000:
Product::with("productType")
->whereHas("productType", function ($query) {
$query->where("product_type_name", "like", "new product");
})
->withCount(["productQuantities as quantity_count" => function ($query) {
$query->selectRaw("sum(quantity)");
}])
->having("quantity_count", ">", 1000)
->get();
you can get through relationship
$product->productType->product_type_name
and attribute:
$product->quantity_count
$products = Product::withsum('productQuantities','quantity')
->leftjoin('product_types','products.product_type_id','=','product_types.product_type_id')
Gives me the result that I wanted. And didn't break the other parts.
But I'm still confused why with() and withSum() didn't work together.
Is it because products belongs to productTypes maybe

Laravel Eloquent Where and orWhere with Eager Load not working well

I've been create JOIN with eager load with these tables
Transactions (parent of transaction_details)
Transaction_details (child of Transaction and parent of Mutasi_logs )
Mutasi_logs (child of transaction_details)
then i add some filters such as :
only show my data (data that has been created by the user logged in)
only show my saldo
only show my amount
I've try with this code
blahlblah.....
->where('created_by',Auth::id())
->orWhere('amount','LIKE','%'.$search.'%')
->orWhere('saldo','LIKE','%'.$search.'%')
but here where condition not working well (show another user's data like my saldo and amount ) when fill the search field.
here is the output :
and here my full code :
MutasiLog::with([
'transaction_detail.transaction',
])
->orWhereHas('transaction_detail', function (&$q) use ($search) {
$q->where('id', 'like', '%' . $search . '%');
$q->orWhereHas('transaction',function($q) use ($search){
$q->where('description','LIKE','%'.$search.'%');
});
})
->where('created_by',Auth::id())
->orWhere('amount','LIKE','%'.$search.'%')
->orWhere('saldo','LIKE','%'.$search.'%')
->offset($start)
->limit($limit)
->orderBy($order,$dir)
->get();
From the docs "You should always group orWhere calls in order to avoid unexpected behavior when global scopes are applied.". You can find an example there.
So you can do something like this:
// blahlblah.....
->where(function ($query) use ($search) {
$query->where('created_by',Auth::id())
->orWhere('amount','LIKE','%'.$search.'%')
->orWhere('saldo','LIKE','%'.$search.'%');
})
// ...
Or maybe this, depends on your needs:
// blahlblah.....
->where('created_by',Auth::id())
->where(function ($query) use ($search) {
$query->where('amount','LIKE','%'.$search.'%')
->orWhere('saldo','LIKE','%'.$search.'%');
})
// ...
when using orWhere and chained with other wheres, you mean : get data where created_by me or where amount like search , this is why get all data ,so the solution you should group search orWhere on single where like this :
->where('created_by',Auth::id())
->where(function($query){
$query->orWhere('amount','LIKE','%'.$search.'%')->orWhere('saldo','LIKE','%'.$search.'%')
})

How can i get query result id in controller from Laravel?

I want to take houses lists and houses pictures on mysql from laravel. But, i have this problem. Using the process below:
$houses = Houses::query()
->orderBy('sort', 'ASC')
->take('6')
->get();
This query, give houses list to me. And I need to use the houses I retrieve to get their photos, this is the best I could think of:
$pictures = Housephotos::query()
->where('house_id', '=', $houses->house_id)
->get();
Question one: This process is correct?
Question two : How can do this?
Add a relation to Houses:
class Houses extends Model
{
public function photos()
{
return $this->hasMany(Housephotos::class);
}
}
and now you can get the photos easily like:
$houses = Houses::query()
->orderBy('sort', 'ASC')
->take('6')
->get();
foreach ($houses->photos as $photo) {
echo $photo->id;
}
the problem with that is, select query will run n times (5 times for this example).
if you add with to the query however, then laravel will run a single in query to get the pictures:
$houses = Houses::query()
->with('pictures')
->orderBy('sort', 'ASC')
->take('6')
->get();
You need to make a relationship between Housephotos and House so that there is house_id in Housephotos. If this is true, you can already use the houses Id you have to retrieve the houses Id:
Say you already have the houses, then you can have:
$pictures = Housephotos::whereIn('house_id', '=', $houses->pluck('id')->toArray())
->get();
This will give you the houses photos.

Laravel 4 - Too much logic in my view template?

i created a search functionality within my Laravel project - the user can search for teamnames or usernames - the result is created and returned like this:
$teams_obj = Team::where('teamname', 'LIKE', '%'.Input::get('searchterm').'%')->get();
$persons_obj = User::where('name', 'LIKE', '%'.Input::get('searchterm').'%')->orWhere('vorname', 'LIKE', '%'.Input::get('searchterm').'%')->get();
return View::make("team.search-content", array('resp' => 'resultlist', 'teams_obj' => $teams_obj, 'persons_obj' => $persons_obj))->with('user', User::find(Auth::user()->id));
Now its getting a little more complicated. I have a database table "relation" which stores if a user is a member of a team via an entry containing user_id and team_id. Laravel knows this relation.
If the search result is displayed within the view, i have to make a distinction if the current user is already a member in the respective team which is displayed in the current row. If the user is already a member within the team he should not be able to apply, otherwise he should have the option to apply.
I solved it with this:
#foreach($teams_obj as $team_obj)
<li data-teamid="{{ $team_obj->id }}">
<span>{{ $team_obj->teamname }}</span>
<?php
$data = ['user_id' => $user->id, 'team_id' => $team_obj->id];
$res = $team_obj->whereHas('Relation', function($q) use ($data) {
$q->where('team_id', '=', $data['team_id']);
$q->where('user_id', '=', $data['user_id']);
})->get();
if (count($res) == 0) {
echo'apply fct available';
}
?>
</li>
#endforeach
I fetch the relation and check if the relation of team_id and user_id is existent. But i have a strange feeling doing this within my view template. What do you think? How can i improve this?
Additionally i think it is strange that i have to make $q->where('team_id'), as I already do $team_obj-> ... but otherwise it is not working correctly.
Any help is appreciated. Thanks!
Do you have any need to show teams that your user cannot apply ? if not you can simply modify your code to get teams that your user is not a member. If you need you can do some checkup in the controller in order to get that information.
I suggest making a foreach for the every team and checking if they have relationship with the user. You can set an attribute in a team to check in the view.
Controller:
foreach($teams_obj as $team_obj){
$res = $team_obj->whereHas('Relation', function($q) use ($data) {
$q->where('team_id', '=', $data['team_id']);
$q->where('user_id', '=', $data['user_id']);
})->get();
if(count($res) == 0)
$team_obj->isApplyableByUser = true;
else
$team_obj->isApplyableByUser = false;
// You can do the same code above in one line, but it's not that compreensive
$team_obj->isApplyableByUser = count($res) == 0;
}
View:
if($team_obj->isApplyableByUser) echo'apply fct available';
Yes, too much logic for a view (in terms of best practices)
Do you have relationships set up for these? Assuming Team hasMany('User')... Why not just eager load your User models?
$teams = Team::with(['users' => function($query){
$query->where('name', 'LIKE', '%'.Input::get('searchterm').'%')
->orWhere('vorname', 'LIKE', '%'.Input::get('searchterm').'%')
}])where('teamname', 'LIKE', '%'.Input::get('searchterm').'%')
->get();
return View::make('your.view', ['teams' => $teams]);
// And in your view.
#foreach($teams as $team)
<li data-teamid="{{ $team->id }}">
<span>{{ $team->teamname }}</span>
#if(!$team->users->count())
apply fct available
#endif
</li>
#endforeach

Categories