Laravel - Retrieve specific data from pivot table - php

I am implemeting a search using Laravel, but couldn't figure out how to get data from my pivot table. The pivot is a many to many relationship between Books and Tags.
The idea here is to search books by tags and display them.
class Book extends Model
{
public function tags() {
return $this->belongsToMany(Tag::class);
}
}
class Tag extends Model
{
public function books() {
return $this->belongsToMany(Book::class);
}
}
Other search seems to work just fine.
$books = Book::where('title', 'LIKE', '%'.$search_text.'%')
->orWhere('author', 'LIKE', '%'.$search_text.'%')
->orWhere('editor', 'LIKE', '%'.$search_text.'%')
->orWhere('ISBN', 'LIKE', '%'.$search_text.'%')
->orWhere('year', 'LIKE', '%'.$search_text.'%')
->orWhere('language', 'LIKE', '%'.$search_text.'%')
->get();

Related

Nested relation whereHas in laravel

I wanna ask about some nested relation using whereHas query in laravel, well for the first I will explain the model first before I going through into my main case.
this is my model :
StockIn.php
class StockIn extends Model {
protected $primaryKey = "id_stock_in";
/* this only column that I wanna show, and skip the else column */
protected $fillable = ['stock_in_id_type'];
public function type_of_items() {
return $this->belongsTo('App\TypeOfitem', 'stock_in_id_type');
}
}
TypeOfItem.php
class TypeOfItem extends Model {
protected $primaryKey = "id_type_item";
/* this only column that I wanna show, and skip the else column */
protected $fillable = ['type_id_item'];
public function items() {
return $this->belongsTo('App\Item', 'type_id_item');
}
public function stock_ins() {
return $this->hasMany('App\StockIn');
}
}
Item.php
class Item extends Model {
protected $primaryKey = "id_item";
/* this only column that I wanna show, and skip the else column */
protected $fillable = ['item_id_common_unit'];
public function common_units() {
return $this->belongsTo('App\CommonUnit', 'item_id_common_unit');
}
public function type_of_items() {
return $this->hasMany('App\TypeOfItem');
}
}
CommonUnit.php
class CommonUnit extends Model {
protected $primaryKey = "id_common_unit";
/* this only column that I wanna show, and skip the else column */
protected $fillable = [/* describe column */];
public function items() {
return $this->hasMany('App\Item');
}
}
I already describe all of my model, as you can see all table (child) have some relation to each parent like :
stockIn -> typeOfItem (relation between child and parent)
typeOfItem -> Item (relation between child and parent)
Item -> CommonUnit (relation between child and parent)
so for the question is how to make some query to getting data in nesting relationship when I do search for all data in child or parent? I already made the query but the result is not same with my expectation or null, it can be said that.
StockInController
$getData = StockIn::with(['type_of_items' => function ($query) {
$query->select('id_type_item', 'type_id_item', 'code_type_of_item', 'type_of_item')
->with(['items' => function ($query) {
$query->select('id_item', 'item_id_common_unit', 'name_item')
->with(['common_units' => function ($query) {
$query->select('id_common_unit', 'name_unit');
}]);
}]);
}])
->with(['stock_out_left_join' => function ($query) {
$query->select('id_stock_out', 'stock_out_id_stock_in');
}])
->whereHas('type_of_items', function ($query) use ($search) {
$query->where('code_type_of_item', 'like', "%{$search}%");
})
->whereHas('type_of_items.items', function ($query) use ($search) {
$query->orWhere('name_item', 'like', "%{$search}%");
})
->whereHas('type_of_items.items.common_units', function ($query) use ($search) {
$query->orWhere('name_unit', 'like', "%{$search}%");
})
->orWhere('created_by', 'like', "%{$search}%")
->orWhere('edited_by', 'like', "%{$search}%")
->get()
->toArray();
Oh ya I will send example data for my query in this bellow :
but when I do search with some keyword is not worked, for example when I do type "adaptor", the result is empty or nothing show on my data, so what I must to do? Thank you
Okay for a while I was think about my problem finally I got the answer. Okay for sharing to everyone I will explain a little bit for the answer.
So the query what I wrote on the controller, I change into this :
$getData = StockIn::with(['type_of_items' => function ($type_of_item) {
$type_of_item->select('id_type_item', 'type_id_item', 'code_type_of_item', 'type_of_item')
->with(['items' => function ($item) {
$item->select('id_item', 'item_id_common_unit', 'name_item')
->with(['common_units' => function ($common_unit) {
$common_unit->select('id_common_unit', 'name_unit');
}]);
}]);
}])
->with(['stock_out_left_join' => function ($stock_out_left_join) {
$stock_out_left_join->select('id_stock_out', 'stock_out_id_stock_in');
}])
->whereHas('type_of_items', function ($type_of_items_search) use ($search) {
$type_of_items_search->where('code_type_of_item', 'like', "%{$search}%")
->orWhere('type_of_item', 'like', "%{$search}%");
})
->orWhereHas('type_of_items.items', function ($items_search) use ($search) {
$items_search->where('name_item', 'like', "%{$search}%");
})
->orWhereHas('type_of_items.items.common_units', function ($common_units_search) use ($search) {
$common_units_search->where('name_unit', 'like', "%{$search}%");
})
->orWhere('created_by', 'like', "%{$search}%")
->orWhere('edited_by', 'like', "%{$search}%")
->get()
->toArray();
As you can see my new query has a new parameter in every with function and I was naming all the parameter with different name, and not like first name before query, so the problem is the ambiguous paramater in every single with function because this query based on nested relation so I must make the parameter name different each other. Or you want make them into split one by one and not using the nested with function you can use this query too, I put on this bellow :
$getData = StockIn::with(['type_of_items' => function ($query) {
$query->select('id_type_item', 'type_id_item', 'code_type_of_item', 'type_of_item');
}])
->with(['type_of_items.items' => function ($query) {
$query->select('id_item', 'item_id_common_unit', 'name_item');
}])
->with(['type_of_items.items.common_units' => function ($query) {
$query->select('id_common_unit', 'name_unit');
}])
->with(['stock_out_left_join' => function ($query) {
$query->select('id_stock_out', 'stock_out_id_stock_in');
}])
->whereHas('type_of_items', function ($query) use ($search) {
$query->where('code_type_of_item', 'like', "%{$search}%")
->orWhere('type_of_item', 'like', "%{$search}%");
})
->orWhereHas('type_of_items.items', function ($query) use ($search) {
$query->where('name_item', 'like', "%{$search}%");
})
->orWhereHas('type_of_items.items.common_units', function ($query) use ($search) {
$query->where('name_unit', 'like', "%{$search}%");
})
->orWhere('created_by', 'like', "%{$search}%")
->orWhere('edited_by', 'like', "%{$search}%")
->get()
->toArray();
I already tried that query and it's work too (with the same name parameter in every single with function).

Laravel Livewire search and filter through relationships

Sorry for my bad english. This is my first post here and I'm a kind of noob in developpment..
Thanks to a lot of reading and some tutorials, I managed to build a small Laravel application.
For various reasons, I decided to include Livewire and it's great.
However, I'm facing some issues in searching and filtering entries from different models and relationships.
Image of what I'm trying to do
I have a model called Seance and I can search through Grade, Theme and Product models (2, 3 & 5 on the image).
My Seance Model :
class Seance extends Model
{
use SoftDeletes;
protected $guarded = [];
public function product()
{
return $this->belongsTo('App\Product');
}
public function theme()
{
return $this->belongsTo('App\Theme');
}
public function specialty()
{
return $this->belongsTo('App\Specialty');
}
public function grade()
{
return $this->belongsTo('App\Grade');
}
public function courses()
{
return $this->hasMany('App\Course');
}
public function category()
{
return $this->belongsTo('App\Category')->withTrashed();
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function specialties(): BelongsToMany
{
return $this->belongsToMany('App\Specialty', 'seance_specialty', 'seance_id', 'specialty_id');
}
public function scopeSearch($query, $term)
{
$term = "%$term%";
$query->where(function($query) use ($term){
$query->where('id', 'like', $term)
->orWhere('name', 'like', $term)
->orWhere('slug', 'like', $term)
->orWhere('subtitle', 'like', $term)
->orWhere('description', 'like', $term)
->orWhereHas('grade', function($query) use ($term){
$query->where('name', 'like', $term);
})
->orWhereHas('product', function($query) use ($term){
$query->where('name', 'like', $term);
})
->orWhereHas('theme', function($query) use ($term){
$query->where('name', 'like', $term);
})
->orWhereHas('category', function($query) use ($term){
$query->where('name', 'like', $term);
});
});
}
}
But I would like to search through the point 4 that is related to 3 and through the point 6 that is related to 5 and I don't know how to do that.
The point 3 is a Model called Theme and it belongs to a Model called Discipline (point 4)
public function discipline()
{
return $this->belongsTo('App\Discipline');
}
The point 5 is a model called Produt and it belongs to a model called Coursetype (point 6)
public function coursetype()
{
return $this->belongsTo('App\Coursetype');
}
I know there is join to do somewhere but I don't exactly know where...
Here's my Livewire component :
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $search = "";
public $paginate = 5;
public $selectedGrade = null;
public $selectedProduct = null;
public $selectedCategory = null;
public $selectedTheme = null;
public $selectedDiscipline = null;
public function render()
{
return view('livewire.seances-table', [
'seances' => Seance::with('product', 'theme', 'specialty', 'grade', 'courses', 'category', 'specialties')
->when($this->selectedGrade, function($query){
$query->where('grade_id', $this->selectedGrade);
})
->when($this->selectedProduct, function($query){
$query->where('product_id', $this->selectedProduct);
})
->when($this->selectedCategory, function($query){
$query->where('category_id', $this->selectedCategory);
})
->when($this->selectedTheme, function($query){
$query->where('theme_id', $this->selectedTheme);
})
->when($this->selectedDiscipline, function($query){
$query->where('discipline_id', $this->selectedDiscipline);
})
->search(trim($this->search))
->paginate($this->paginate),
'grades' => Grade::all(),
'products' => Product::all(),
'categories' => Category::all(),
'themes' => Theme::all(),
'disciplines' => Discipline::all()
]);
}
Also, I would like to filter through the Disciplines (point 4) but I get this error.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'discipline_id' in 'where clause'
I know why I'm getting this error, but I don't know how to fix it.
Sorry if all this is not very clear.
Any help would be much appreciated.
Thanks you all and cheers from France
since discipline_id is under themes table which is related to Seance model.
I suggest doing
$query->where('theme.discipline_id', $this->selectedDiscipline);

Why does my whereHas query error out with undefined method "getHasCompareKey()"?

I have a model Job which is attached to one model Project.
Here are the class definitions:
class Job extends Model
{
public function project() {
return $this->belongsTo('App\Project');
}
}
class Project extends Model
{
public function jobs() {
return $this->hasMany('App\Job');
}
}
I'm trying to query the Jobs collection and filter on either jobs.title or project.title.
Here is my current search query:
$jobs = Job::where(function($query) use ($searchTerm) {
$query->where('title', 'LIKE', $searchTerm)
->orWhereHas('project', function ($subQuery) use ($searchTerm) {
return $subQuery->where('title', 'LIKE', $searchTerm);
});
})->get();
However, this is returning an error:
Call to undefined method Jenssegers\Mongodb\Query\Builder::getHasCompareKey()
I think you need to clean up your code a bit:
$jobs = Job::where('title', 'LIKE', $searchTerm)
->orWhereHas('project', function ($query) use ($searchTerm) {
$query->where('title', 'LIKE', $searchTerm);
})->get();

How to select all records with relation and where clause Laravel MySQL

I'm new to Laravel so I have a bit of a problem. I have tables 'Categories' and 'Products' in my DB. In my models I setup the relations like:
Product.php:
public function category()
{
return $this->belongsToMany(Category::class);
}
Category.php:
public function products()
{
return $this->hasMany(Product::class);
}
What I need now is that I want to select all of the Categories with their related Products. (User enters in search bar category name and gets list of Categories and when user selects Category I get all of the columns from Categories and ALSO Products related with this Category).
I have tried something like this:
public function findCategory(Request $request)
{
return Category::with('products')
->where('name', 'like', '%' . $request->category_name . '%')
->limit(15)
->get();
}
ALSO:
public function findCategory(Request $request)
{
return Category::where('name', 'like', '%' . $request->category_name . '%')
->products()
->limit(15)
->get();
}
But this doesn't seem to work and I ran out of ideas. Does anyone know if there is a way to do this? Any help would be much appreciated :)
it would be something like
public function findCategory(Request $request)
{
$term = $request->category_name;
return Category::with('products')->where(function($q) use($term) {
$q->where('categories.name','like',"%$term%");
})->paginate(15); //or use limit(15)
}
Your query is almost complete except that you didn't load related model. Therefore, you last example should be:
public function findCategory(Request $request)
{
return Category::where('name', 'like', '%' . $request->category_name . '%')->
->with('products') //load related products
->limit(15)
->get();
}
public function getAllData()
{
$data = tableName::where('Method','Delivery')->get();
return response()->json($data, 200);
}
OR
$users = DB::table_Name('users')->select('name', 'email as user_email')->get();

Searching from model and related model in laravel5

I want to keyword search from a table and its all related table using Elequent in Laravel5.
My controller is
$clients = Client::with('contacts', 'paymentTerm', 'addressInfo');
if ($q = Request::input("q")) {
$clients->where("clients.name", 'LIKE', "%$q%");
$clients->where("address_info.email", 'LIKE', "%$q%");//This is not working,I want to search from both client and client address_info
}
return $clients->paginate(10);
Client Model ,
public function addressInfo() {
return $this->hasOne('App\Model\ClientAddressInfo');
}
Client Address info,
public function client() {
return $this->belongsTo('App\Model\Client');
}
how can I apply keyword search here?
You can use whereHas to filter by a related model:
$clients->whereHas('addressInfo', function($query) use ($q){
$query->where("email", 'LIKE', "%$q%");
});

Categories