Laravel Eloquent where in relationship may or may not have result - php

I've got this relation:
A Company may have one or more Employees.
I need to SELECT Companies based on the first_name of an Employee, but not show it when the first_name of the employee doesn't match.
This is what I currently have.
$companies = Company::with(array('employees' => function($q) {
$type = (!empty(Input::get('company_search_employee'))) ? '%' . Input::get('company_search_employee') . '%' : '%';
$q->where( 'employees.first_name', 'LIKE', $type);
}))->get();
The employee first_name must be neglected if the Company doesn't have any Employees
But it shows the Company data, even if the employee doesn't match. the employee just gets hidden.
How would I go on doing this?

Try that way:
$companies = Company::whereHas('employees', function($q){
$type = (!empty(Input::get('company_search_employee'))) ? '%' . Input::get('company_search_employee') . '%' : '%';
$q->where( 'first_name', 'LIKE', $type);
})->get();
or if it doesnt work add 'employees' to where clause:
$q->where('employees.first_name', 'LIKE', $type);

Related

Multiple search clause for many-to-many relationships in Laravel

Good day. I have this stuff that has been a little bit problematic for me in my application. I have a Staff model which has a many to many relationship with a Company model. Hence, I have a company_staff table.So, the companies have a unique identifier which is the company code.
The Staff model has information such as first name, lastname, and email etc. Now, I want to perform a search operation using either the firstname, lastname or email, but fetching data for only the company with the unique code (i.e search only within that company). This is the query I came up with below:
$users = Staff::where('first_name', 'like', '%' . $request->search_term . '%')
->orWhere('last_name', 'like', '%' . $request->search_term . '%')
->orWhere('email', 'like', '%' . $request->search_term . '%')
->whereHas('coporate', function ($q) use ($company_code) {
$q->where('company_code', $company_code);
})->get();
I get results but this only returns all the result that match from my "staff" table, behaving as if the "company_code" part of the query does not exist at all. However, if I leave the query as :
$users = Staff::where('first_name', 'like', '%' . $request->search_term . '%')
->whereHas('coporate', function ($q) use ($company_code) {
$q->where('company_code', $company_code);
})->get();
I get the desired result. But, I want to be able to search with both last_name and email as well. Please, how do I go about this?
Try with this code
$users = Staff::where(function ($query) use($request) {
$query->where('first_name', 'like', '%' . $request->search_term . '%')
->orWhere('last_name', 'like', '%' . $request->search_term . '%')
->orWhere('email', 'like', '%' . $request->search_term . '%');
})->whereHas('coporate', function ($q) use ($company_code) {
$q->where('company_code', $company_code);
})->get();
For more : https://laravel.com/docs/6.x/queries#parameter-grouping

Can anyone help me to solve an ambiguous error when search?

$students = Student::select('students.*', 'users.email')->join('users', 'students.user_id', 'users.id')->orderBy("id", "desc")->skip($page * $pageSize)->take($pageSize);
if (request('se') != "" || request('se') != null) {
$se = request('se');
$se = str_replace("+", " ", $se);
$students = $students
->where(function ($q) use ($se) {
$q->where('students.student_number', 'like', '%' .$se. '%')
->orWhere(DB::raw("CONCAT(`first_name`, ' ', `last_name`)"), 'LIKE', '%' . $se . '%')
->orWhere('students.gender', $se)
->orWhere('students.phone', 'like', '%' .$se. '%')
->orWhere('email', 'like', '%' .$se. '%');
});
}
$students = $students->orderBy('id', 'DESC')->get();
when I search in the list I got Integrity constraint violation: 1052 Column 'first_name' in where clause is ambiguous error.
This got when join the table because both students and users table have first name and last name columns, but I have retrieved from only students table, I didn't understand why this appears again!
Are there any better solution for this?
Change the first_name and last_name to students.first_name and students.last_name respectively

Fetch data from same field name in two different tables and detect which filed name we mean

I have assigned search method for my application and i have made relationship between two tables "users " table and "posts" table both of them have same field name "created_at" and when i want to fetch data that when this post has been created it will bring the date in users table created_at field not in posts table created_at field.
All i want is how to tell the system make difference between which table field name i mean .
This date comes from created_at field in users table
I wand to come date in this created_at field in posts table
ListingController.php
public function search(Request $request){
$posts = Post::with(['comments','category','creator'])
->join('users', 'posts.created_by', '=', 'users.id')
->where('slug', 'LIKE', '%'.$request->search. '%')
->orWhere('users.name', 'LIKE', '%'.$request->search. '%')
->where('status',1)->orderBy('posts.id','DESC')->paginate(5);
return view('front.listing',compact('posts'));
}
listing.blade.php
<div class="article_date">
by: {{ $post->creator->name }} , {{$post->created_at->diffForHumans()}}
</div>
You are calling your relationship improperly. You should not use a join there. Use constrained eager loading instead
There will be no conflict in the created_at date since there will be no join.
While still keeping your search query inside the closure of the relationship.
$posts = Post::with(['comments', 'category'])
->with(['creator' => function ($query) use ($request) {
$query->where('name', 'LIKE', '%' . $request->search . '%');
}])
->where('slug', 'LIKE', '%' . $request->search . '%')
->where('status', 1)
->orderBy('id', 'DESC')
->paginate(5);

Laravel Search Reference Second Model/Collection/Table with orWhereHas?

I'm trying to implement search functionality within my blade for my Script model. It performs fine for everything related to searching directly within the Script collection/table. However, my users also will need to be able to enter in a Patient first_name or last_name and search for the script records within the Script table that belong to the Patient being searched for. These are connected with a hasMany/belongsTo relationship. I'm trying to reference data from the Patient table in the Script results.
I've tried (with help from SO already) to implement orWhereHas and reference the patients table, but something with my syntax must be off.
The error messages I'm getting from trying to reference 'patients' with orWhereHas returns:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'scripts.patients_id' in 'where clause' (SQL: select count(*) as aggregate from `scripts` where exists (select * from `patients` where `scripts`.`patients_id` = `patients`.`id` and (`first_name` like %% or `last_name` like %%)))
This probably would work if it referenced patient_id, which is the column name for the patients foreign key. I don't know if there is a way to do that?
When I change 'patients' to 'patient', I receive the error:
Call to undefined method App\Script::patient()
Models
Patient hasMany Script
Script belongsTo Patient (patient_id)
Script Blade
{{ Form::text('search', $search, ['class' => 'form-control form-control-sm', 'placeholder' => 'Search Scripts...']) }}
{{Form::submit('Search', ['class' => 'btn btn-primary btn-sm'])}}
ScriptController
$search = $request->search;
$patients = Patient::all();
$scripts = Script::
when($search, function ($query) use ($search) {
$query->where(function ($query) use ($search) {
$query
->where('prescribe_date', 'LIKE', '%' . $search . '%')
->orWhere('status', 'LIKE', '%' . $search . '%')
->orWhere('efax_reference', 'LIKE', '%' . $search . '%')
->orWhere('efax_confirmation', 'LIKE', '%' . $search . '%');
});
})
->orWhereHas('patients', function ($query) use ($search) {
$query->where('first_name', 'like', '%' . $search . '%')
->orWhere('last_name', 'like', '%' . $search . '%');
})
->paginate(25);
I expect that if someone searches for a patient name within the search input on the Scripts table/model, they are able to cross-reference the Patients table/model and display the Scripts records that are foreign_key'ed to those Patients.
EDIT:
Patient model
// One Patient has Many Scripts relationship
public function scripts() {
return $this->hasMany('App\Script');
}
Script model
// Many Scripts to One Patient relationship
public function patients() {
return $this->belongsTo('App\Patient');
}

Laravel Query builder, how to have 1 leading where and the other orwhere?

I'm having a problem with my query.
I want to filter through all Orders where user_id is the authenticated user. And run the searchquery on field number1 and field number2.
Query:
$query = Order::query();
$query->where('user_id', Auth()->id())
->where('number','LIKE', '%' . $searchquery . '%')
->orWhere('number2,'LIKE', '%' . $searchquery . '%')
->with('user');
I want to ALWAYS check where user_id is Auth()->id();
But when i run this orWhere it also gets orders from other users.
Thanks in advance.
Do it like this :
$query = Order::query();
$query->where('user_id', Auth()->id())
->where(function ($query) use ($searchquery) {
$query->where('number','LIKE', '%' . $searchquery . '%');
$query->orWhere('number2,'LIKE', '%' . $searchquery . '%');
})
->with('user');

Categories