where clause inside a relationships - laravel - laravel

I have 3 models like this:
WarehousePivotCategory:
id - warehouse_id - warehouse_category_id
Warehouse:
title
WarehouseCategory:
title_en
I've created 2 hasOne relationships inside WarehousePivotCategory and they work fine:
public function Warehouse()
{
return $this->hasOne('App\Models\Warehouse','id','warehouse_id');
}
public function WarehouseCategory()
{
return $this->hasOne('App\Models\WarehouseCategory','id','warehouse_category_id');
}
in the database I have two records in warehouses table :
id title
1 AA
2 BB
I want to search title in warehouses :
$title = 'AA';
$warehouses = WarehousePivotCategory::with(['warehouse' => function($q) use ($title) {
$q->where('title', 'like', '%' . $title . '%');
},'WarehouseCategory'])->get();
foreach ($warehouses as $w)
{
echo $w->warehouse->title; // no thing
}
but it doesn't return any of title of warehouses.
my relationships is correct because below code works fine :
WarehousePivotCategory::with('warehouse','WarehouseCategory')->paginate(10);

I think you're missing get method in your closure. Try it like this:
$warehouses = WarehousePivotCategory::with(['warehouse' => function($q) use ($title) {
$q->where('title', 'like', '%' . $title . '%')->get(); },'WarehouseCategory'])->get();
You can also send array of fields you want to fetch to get method, like this:
$warehouses = WarehousePivotCategory::with(['warehouse' => function($q) use ($title) {
$q->where('title', 'like', '%' . $title . '%')->get(['id', 'title']); },'WarehouseCategory'])->get();

That is wrong. You don't need to use hasone while you have created pivot.You need to use BelongsToMany
class warehouse extends Model{
public function ware_cat(){
return $this->BelongsToMany('App\Models\WarehouseCategory');
}
public function getWarehouse(){
$this->with('ware_cat')->get();
}
}
Pivot table will fetch it so in warehouse model you will get its category and in category model you will get the warehouse same way visa-versa.

Related

Livewire checkbox filter to relation model

I have a Livewire component with search field whick works like a charm, and above that I have a list of Location model. /locations. Also, I have a relation table Categories with category_id. Now, i want to implement checkbox filter on same page with category (catA, catB, catC). I maked a Livewire component with
PLease can you help me. Thanky much
class LocationSearch extends Component
public $searchTerm = "";
public $locations;
public $categories = [];
public function render()
{
sleep(1);
$searchTerm = '%' . $this->searchTerm . '%';
$this->locations = Location::query()
->where('name', 'LIKE', "%{$searchTerm}%")
->orWhere('description', 'LIKE', "%{$searchTerm}%")
->orWhere('visibility', 'LIKE', "%{$searchTerm}%")
->get();
return view('livewire.location-search', [
]);
}

Probleme of pagination (Laravel)

I have a problem with my pagination, i have my every page displayed, when i want go to other page my search is canceled and it displays all the elements of the site.
<?php
namespace App\Http\Controllers;
use App\Models\Furniture;
use Illuminate\Http\Request;
use App\Models\Tag;
class MainController extends Controller
{
public function showHomepage()
{
$latestProducts = Furniture::latest()->take(5)->get();
return view('templates.homepage', compact('latestProducts'));
}
public function showFurniture(Furniture $furniture)
{
return view('templates.furniture', compact('furniture'));
}
public function showSearchResults(Request $request)
{
$search = $request->get('q');
$tag = Tag::where('title', 'like', '%' . $search . '%')->first();
$query = Furniture::select("furniture.*")
->join("furniture_tag", "furniture_tag.furniture_id", "=", "furniture.id");
if ($tag){
$query->where('furniture_tag.tag_id', $tag->id);
}
$query->orWhere('furniture.title', 'like', '%' . $search . '%');
$furnituresCount=$query->count();
$furnitures=$query->paginate(5);
return view('templates.search', compact('search', 'furnitures', 'furnituresCount',));
}
}
To append all of the current request's query string values to the pagination links you need to change
$furnitures=$query->paginate(5);
to
$furnitures = $query->paginate(5)->withQueryString();
Manual: Appending Query String Values

How in Laravel filter by relationship?

I have two models which linked with each other:
class Task extends Model{
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
}
class User extends Model{
public function tasks(){
return $this->hasMany('App\Task', 'user_id');
}
}
Now I want to create some search or filter system.
There is a form where the user can choose Task only then the User's parameters (age, sex etc)
How can I do this kind of things? I tried to use newQuery on relation but...
Any help, thanks
I hope i understood you well.
Use nested where and whereHas as such
$tasks = Task::where('condition', $var)
->orWhereHas('user', function($q) use ($var){
$q->where('condition', 'LIKE', '%'. $var.'%');
});
try this. i hope it will work for you.
use join to get data from two tables
function getBuildings($request) {
if (isset($request->keyword) && $request->keyword != '') {
$data = $this->where(function($query) use ($request) {
$query->orWhere('users.column_name', 'LIKE', '%' . $request->keyword . '%');
$query->orWhere('users.column_name', 'LIKE', '%' . $request->keyword . '%');
});
}
$datacount = $this->count();
$dataArray = $this->select('users.*,task.whatever data you want to get from task');
if ($request->length == -1) {
$dataArray = $dataArray->get();
} else {
$dataArray = $dataArray->skip($request->start)->take($request->length)->get();
}
return [$datacount, $dataArray];
}

Search records in muliple tables from a single search form

I have these two tables named posts and events, both tables are not related at all and I want users to be able to search from these two tables using a single search form. Here is what I've got so far :
public function search(Request $request) {
$input = trim($request->input('q'));
$keywords = strtolower($input);
$keywordArr = explode(' ', $keywords);
if (!empty($keywords)) {
foreach($keywordArr as $key) {
$posts = Post::where('title', 'LIKE', '%' . $key . '%')->get();
$events = Event::where('title', 'LIKE', '%' . $key . '%')->get();
}
return view('search/results', compact('posts','events','keywords'));
}
return redirect()->back();
}
That method doesn't work as expected. If both tables has records that match users keywords this method will only return result from events table. How do I solve this ? that's all and thanks!
If you are using laravel searchable package,try this method.
Controller file.
public function searchFunction(Request $request)
{
$result= ModelName::search($search)->get();
}
Model file.
class ModelName extends Model
{
use SearchableTrait;
protected $searchable = [
'columns' => [
'posts.title' => 10,
'events.title' => 9
]
];
}
You should consider using Laravel Scout: https://laravel.com/docs/5.5/scout
It would help making your search much faster and way more relevant compare to a LIKE query with MySQL.

query search LIKE use keywords where and left join LARAVEL 5

I want to find a data from two tables based on the name contained in the users, but I am having problems.
This is the users table containing the id, and name.
This is the student table that contains the id, and user_id.
Where user_id student = id users.
public function search(Request $request)
{
$keywords = trim($request->input('keywords'));
if (!empty($keywords)) {
$id_class = $request->input('id_class');
//Query
$query = User()
->leftjoin('student', 'users.id', '=', 'student.user_id')
->where('users.name', 'LIKE', '%' . $keywords . '%');
(!empty($id_class)) ? $query->Kelas($id_class) : '';
$data_student = $query->paginate(10);
//URL link pagination
$pagination = (!empty($id_class)) ? $pagination = $data_student->appends(['id_class' => $id_class]) : '';
$pagination = $data_student->appends(['keywords' => $keywords]);
$amount_data = $=data_student->total();
return view('student.index', compact('data_student', 'keywords', 'pagination', 'amount_data', 'id_class'));
}
return redirect('student');
}
Call to undefined function App\Http\Controllers\User()
As mentioned previously you need to correctly refer to the User class with namespace, you also need to change thew following:
$query = User()
->leftjoin('student', 'users.id', '=', 'student.user_id')
->where('users.name', 'LIKE', '%' . $keywords . '%');
to:
$query = User::leftjoin('student', 'users.id', '=', 'student.user_id')
->where('users.name', 'LIKE', '%' . $keywords . '%');
You must call the first method on the class as static with ::.
Also another potential typo you join the table student should it be plural; students?

Resources