Joining two models in Laravel Eloquent - php

I have a model stored in a variable like:
$user = User::where('name', 'like', $test)
->orderBy('name');
I would like to build another query where I can join $user. Can't find the right syntax to do it.
What am trying to achieve:
$numbers= Number::join($user, $users.id, '=', 'number.user_id')
->where('name', 'like', "%" . $validated['text'] . "%")])
->get();

Assuming you have typical hasMany/belongsTo relationships set up between User and Number models, this should work:
User::where("name", "like", $test)
->whereHas("numbers", function($q) {
$q->where("name", "like", "%$validated[text]%");
})
->with("numbers", function($q) {
$q->where("name", "like", "%$validated[text]%");
})
->get();
The where() method, of course, matches users with the desired name. The whereHas() method further restricts based on the relationship, looking only for users having numbers with a matching name. Assuming you want to retrieve those matching numbers, you have to do the same filter again on the eager load.

Try this,
$numbers= Number::whereHas('<Your Eloquent Model>',function($query)use($validated){
$query->where('name', 'like', "%" . $validated['text'] . "%")]);
}
->get();

Join can be written in this way
$records = User::select('users.*')
->where('users.name', 'like', $test)
->join('numbers', function($join) {
$join->on('users.id', '=', 'numbers.id')
->where('numbers.name', 'like', "%" . $validated['text'] . "%");
})
->get();

Related

How can i find only deleted rows in Laravel?

I'm using SoftDeletesin my projects, which is recognized as deleted_at in database table, I want to search and find only deleted rows.
Here is my controller code
public function trashedJobSearch(Request $request)
{
$search = $request->get('search');
$jobs = Jobs::select('id', 'company_name', 'position_name', 'job_description','deleted_at', 'created_at', 'expire_date', 'status')
->where(DB::raw('lower(company_name)'), 'like', '%' . mb_strtolower($search) . '%')
->orWhere(DB::raw('lower(position_name)'), 'like', '%' . mb_strtolower($search) . '%')
->where('deleted_at', '!=', null)
->paginate(10);
return view('/trashed', compact('jobs'));
}
I tried to use onlyTrashed() but it's not working either.
As you have orWhere you need to use a grouping and also onlyTrashed
Jobs::select('id', 'company_name', 'position_name', 'job_description','deleted_at', 'created_at', 'expire_date', 'status')
->where(function ($query) use ($search) {
$query->where(DB::raw('lower(company_name)'), 'like', '%' . mb_strtolower($search) . '%')
->orWhere(DB::raw('lower(position_name)'), 'like', '%' . mb_strtolower($search) . '%');
})->onlyTrashed()
->paginate(10);
The onlyTrashed() method should work for you. Docs for Laravel deleted entries. I have seen times where adding the raw select statement screws it up though.
Take out the extra bits with the select and DB::raw and then add them in after you have what you need. Start with the simplest:
$testOfDeletedOnlyJobs = Jobs::onlyTrashed()->get();
From here, add in the other parts of your query to see where and why it fails. If the above gives you nothing, perhaps there are no deleted records?
You can use
Model::onlyTrashed()->get();
Did you have looking for this post yet?
How to get all rows (soft deleted too) from a table in Laravel?
You can try this.
In your Model-
use Illuminate\Database\Eloquent\SoftDeletes;
class ModelName extends Model
{
use SoftDeletes;
}
To get only deleted rows
$search = $request->get('search');
$data = App\ModelName::onlyTrashed()
->where('id', $search)
->get();

Laravel where clause is not returning data after multiple orWhere clauses?

I am using laravel 6.10 version in that I am implementing search,
I have 3 tables
1) course_category
2) course_sub_category
3) course [course_id_category(foreign key),course_sub_category_id(foreign key)]
below is my code
$course = $request->searchItem;
if ($course=="") {
$Courses = DB::table('course')
->join('course_category', 'course.course_category_id', '=', 'course_category.id')
->select('course.*','course_category.title as category_title','course_category.thumb as category_thumb')
->orderBy('course.title','asc')
->paginate(15);
}
else{
$Courses = DB::table('course')
->join('course_category', 'course.course_category_id', '=', 'course_category.id')
->join('course_sub_category', 'course.course_sub_category_id', '=', 'course_sub_category.id')
->select('course.*','course_category.title as category_title','course_category.thumb as category_thumb')
->where('course.title', 'LIKE', '%'.$course.'%')
->orWhere('course_category.title', 'LIKE', '%'.$course.'%')
->orWhere('course_sub_category.title', 'LIKE', '%'.$course.'%')
->get();
}
when i am retunring the values i am gatting 0 arrays but when i am removing one orwhere from existing my query is working and its returnig we all values with match
means when i am using multiple orWhere in laravel my where is not working, please share the solution on same.
->orWhere doesnt work like typical SQL. You should use it like that:
$Courses = DB::table('course')
->join('course_category', 'course.course_category_id', '=', 'course_category.id')
->join('course_sub_category', 'course.course_sub_category_id', '=', 'course_sub_category.id')
->select('course.*','course_category.title as category_title','course_category.thumb as category_thumb')
->where(function($query) use ($course){
$query->where('course.title', 'LIKE', '%'.$course.'%')
$query->orWhere('course_category.title', 'LIKE', '%'.$course.'%')
$query->orWhere('course_sub_category.title', 'LIKE', '%'.$course.'%')
})
->get();

how to limit the number of data in where has query laravel

I have a query like so
$data = City::with('hotel')->orwherehas('hotel', function ($query) use ($user_input) {
//here i want to limit this result to 5
$query->where('name', 'LIKE', '%' . $user_input . '%')->take(5);
// $query->take(5); i have tried this too
})->orWhere('name', 'LIKE', '%' . $user_input . '%')->get();
inside the whereHas clause, I have a query that I want to limit to 5, now I tried limit, take but no luck after that where nothing is working I don't know why
You can pass your query to the ->with() query builder method:
$data = City::with(['hotel' => function($query) use ($user_input) {
$query->where('name', 'LIKE', '%' . $user_input . '%')->limit(5);
}])
->where('name', 'LIKE', '%' . $user_input . '%')
->get();
This will get all hotels associated with a city which have the user input, where the city contains the user input.
Note that the ->orWhere() is not used here.

Laravel Eloquent - Conditional Data Fetching

I've a customer and customer group table. I want to search the customers based on term/filter text.
Say, there is two customer_group_id, 7 and 8. When 8, I'll need to find mobile fields in orWhere clause, otherwise not.
What I've tried is
$contacts = Contact::where(function ($query) use ($term) {
$query->where('contacts.name', 'like', '%' . $term .'%')
});
// For customer_group_id=8
$contacts->when('customer_group_id=8', function($q) use ($term){
return $q->orWhere('mobile', 'like', '%' . $term .'%');
});
The when() is not working. It showing all the results. I know that I've to pass any boolean value in the when() functions first parameter.
Is there any solution for this problem? Or what is the other way I can get the data's.
The when() method doesn't add an if statement to your query, it is just a way to save you from writing an if statement in your code.
To achieve what you're after you can use nested orWhere() clause:
$contacts = Contact::where('name', 'like', '%' . $term . '%')
->orWhere(function ($query) use($term) {
$query->where('customer_group_id', 8)->where('name', 'like', '%' . $term . '%');
})
->get();
If there is more to your query than what you've put in your question then you can simply wrap the above in another where clause:
$contacts = Contact::where(function ($query) use ($term) {
$query->where('name', 'like', '%' . $term . '%')
->orWhere(function ($query) use ($term) {
$query->where('customer_group_id', 8)->where('name', 'like', '%' . $term . '%');
});
})
->where('some column', 'some value')
->get();

Laravel Eloquent Search Multiple Related Tables

I am struggling with figuring out how to run a like query against multiple related tables.
I have a submissions table that has related users, mcd_forms, and submission_statuses tables.
Here is my code for running a LIKE statement with the given $terms_like.
$submission = new Submission;
$terms_like = '%'.$search_terms.'%';
$data['submissions'] = $submission
->join('users as users', 'users.id', '=', 'submissions.user_id')
->join('mcd_forms as forms', 'forms.submission_id', '=', 'submissions.id')
->join('submission_statuses as statuses', 'statuses.id', '=', 'submissions.submission_status_id')
->where(function($q) use ($terms_like) {
$q->where('users.user_group_id', '=', Auth::user()->user_group_id)
->orWhere('forms.name', 'like', $terms_like)
->orWhere('forms.custom_id', 'like', $terms_like)
->orWhere('forms.start_date', 'like', $terms_like)
->orWhere('forms.end_date', 'like', $terms_like)
->orWhere('forms.soft_sell_date', 'like', $terms_like)
->orWhere('forms.region', 'like', $terms_like)
->orWhere('statuses.status_formatted', 'like', $terms_like);
});
No matter what I try it returns incorrect results. What am I doing wrong?
In your query above, since you are not using the "%" symbol, your like clause is working as an "=" since it's trying to match the whole word.
Replace all the "where" clause like this:
->orWhere('forms.name', 'like', "%".$terms_like."%")
This will try to match the word anywhere in the text.
You can try 'like' operator following this:
$users = DB::table('users')
->where('forms.name','LIKE', '%'.$terms_like.'%')
->get();

Categories