How to show value from laravel eloquent relationship - laravel

I have tables like this
products - id, name, description, category_id, brand_id, color_id, material_id, price
extras - id, product_id, size_id, stock
images - id, product_id, name, path
size - id, name
Model product :
public function extra()
{
return $this->hasMany('App\Extra', 'product_id', 'id');
}
public function image()
{
return $this->hasMany('App\Image', 'product_id', 'id');
}
Model extra :
public function size()
{
return $this->hasOne('App\Size', 'id', 'size_id');
}
public function product()
{
return $this->belongTo('App\Product', 'product_id', 'id');
}
Model image :
public function product()
{
return $this->belongsTo('App\Product', 'product_id', 'id');
}
how to get the size name, image name & path value from the extras and images tables?
I can get the size name using this query echo $product['extra'][0]['size']['name'];, but I only get one value I don't know how to loop to get all the value.
$products = Product::with(['brand', 'category', 'color', 'image', 'material', 'extra', 'user'])->get();
foreach ($products as $product)
{
echo $product['name'] ." ". strip_tags($product['description']) ." ". $product['category']['name'] ." ". $product['brand']['name'] ." ". $product['color']['name'] ." ". $product['material']['name'] ." ". $product['price'] ." ". $product['sku'] ." ". $product['user']['name'] ."</br>";
echo $product['extra'][0]['size']['name'];
}
Any suggestion what I need to do or something that I can read to solve thiat? Thank you.

I believe below code will work for you :
// Extra relationship in Product.php
public function extra()
{
return $this->hasMany('App\extra', 'product_id', 'id');
}
// To get product extra with eager loading
$products = Product::with(['extra', 'extra.size'])->get();
foreach ($products as $product)
{
foreach ($product->extra as $extra){
echo $extra->size->name
}
}

The product contains multiple values of each relation you implement 'with' so run foreach loop or try this for a specific result
$products-brand->where("SOME CONDITION")->get();

Related

Search Query by Child field Eloquent relation

My Product Model is
public function IncomeRepo(){
return $this->hasMany(Income::class,'Product');
}
My Income Report Model Is
public function ProductData(){
return $this->belongsTo(Product::class,'Product','id');
}
My Query is
public function SearchIncomeData(Request $request){
$GetFromDate = $request->FromDate;
$GetToDate = $request->ToDate;
$ProductData = Product::with('IncomeRepo')->whereBetween('created_at', [$GetFromDate, $GetToDate])->get();
return view('Admin.Report.ProductSalesReport',compact('ProductData'));
}
When I return $ProductData it return products table created_at Data. BUT I nee Income table created_at data which be multiple
How can I get it?
My expectation show incomes table created_at data
If you want to filter data by child tables date then you need to use whereHas relationship.
$GetFromDate = $request->FromDate;
$GetToDate = $request->ToDate;
$ProductData = Product::with('IncomeRepo')
->whereHas('IncomeRepo',function($que) use($GetFromDate,$GetToDate) {
$que->whereBetween('created_at',[$GetFromDate, $GetToDate])})->get();
return view('Admin.Report.ProductSalesReport',compact('ProductData'));
In controller. (Use whereBetween)
public function SearchIncomeData(Request $request)
{
$GetFromDate = $request->FromDate;
$GetToDate = $request->ToDate;
$ProductData = Product::with(['IncomeRepo' => function ($query) use ($GetFromDate, $GetToDate)
{
$query->whereBetween('created_at', [$GetFromDate, $GetToDate]);
}
])->get();
return view('Admin.Report.ProductSalesReport', compact('ProductData'));
}
In view
foreach ($ProductData as $product)
{
foreach ($product->IncomeRepo as $income)
{
echo $income->created_at;
}
}

Laravel Eloquent how to get all parents

I have relation like this:
DB relation
I have a code in my model that retrieves me just one parent:
public function AllParents()
{
return $this->belongsToMany($this, 'parent', 'product_id', 'parent_id')
->select('parent', 'name');
}
I get it in my controller like this:
private function product(Product $product)
{
return $product->Product()
->with('AllParents')
->get();
}
Finally I need data like this:
Product1/Product_2/Product_3
I think I need a loop, but how to do it in Eloquent?
Just change relationship. You have mentioned pivot table name wrong one.
public function AllParents()
{
return $this->belongsToMany(Product::class, 'Product_parent', 'product_id', 'parent_id') ->select('parent', 'name');
}
and then you can access
\App\Models\Product::with('AllParents')->get()
In your Product Model. You have define relationship like this.
public function allParents()
{
return $this->belongsToMany(Product::class, 'product_parents', 'product_id', 'parent_id')->select('name');
}
And, In Controller you can get all the parents with eager loading.
Product::with('allParents')->find($productId);
And, In View you can use foreach loop to iterate every parent object.
#foreach ($product->allParents as $parentProduct)
{{ $parentProduct->name }}
#endforeach
I did like this:
I modified my controller
private function product(Product $product)
{
$allParents = [];
$parent = null;
$parent->$product->Product()->with('AllParents')->first()->id;
while ($parent != null) {
array_push($allParents, Product::all->find($parent));
$parent = Product::all()->find($parent) - first();
}
}

laravel multiple relation query

I have 3 model in my project and i want to get a query or collection result as i say:
JewelsItem model:
protected $table = 'jewel_items';
public function jewel(){
return $this->belongsTo('App\Models\Jewel');
}
public function sellInvoice(){
return $this->belongsTo(SellInvoice::class,'sell_invoice_id');
}
2.Jewel model:
public function jewelsItems(){
return $this->hasMany('App\Models\JewelsItem');
}
3.sellInvoice model:
protected $table = "sell_invoices";
public function jewelsItems(){
return $this->hasMany(JewelsItem::class,'buy_invoice_id');
}
Query: i want to get all jewelsitems that has no sellInvoice and has jewel name like 'something'.
note: jewel model has a name attribute .and i want to add name of jewel to first of all the collection's items of result.
i know how to get all jewel with name of 'something' :
Jewel::where('name','like','something'.'%')->get();
but i can't get all jewelItem related to it an add name of jewel to first of them.
To look for condition in another relationship you can use whereHas() and whereDoesntHave()
$name = 'something';
$items = JewelsItem::whereHas('jewel', function($query) use ($name) {
$query->where('name', 'LIKE', "%{$name}%");
})
->whereDoesntHave('sellInvoice')
->with('jewel')
->get();
It reads: getting jewel items where jewel has $name in the name field
and doesn't have sell invoice
then add related jewel to the jewel item.
When you want to retrieve the name of the jewel, you can access its property like so.
foreach($items as $item) {
echo $item->jewel->name;
}

Advanced Select statement (Laravel)

In the Products table i have the store_id column which connects the product with the store.
In my APIController which i use with Angular i have this return statement. I am returning a collection of products.
return Product::where('category_id', $category->id)
->select(array('id', 'name', 'newprice', 'image',
'store_id', 'link'))
->paginate(20);
My problem is that instead of returning the store_id(from the products table) i want to return the store name, which is NOT stored in the same table. Is there any way to do that?
Is my only option the use of JOIN?
I recommend you do it with Laravel(/Eloquent) relationships like this:
ApiController:
$productFieldArray = ['id', 'name', 'newprice', 'image', 'store_id', 'link'];
$product = Product::where('category_id', $category->id)
->select(productFieldArray)
->paginate(20);
// Get the value you want (I guess it's the name attribute?)
$store = $product->store->name;
Model relationships:
Product.php:
...
public function store() {
return $this->belongsTo('App\Store');
}
...
Store.php:
...
public function products() {
return $this->hasMany('App\Product');
}
...
Edit:
You have to use the with() function in your query to point out your want to receive the store data too. See: Laravel - accessing relationship Models with AngularJS or http://laravel.com/docs/4.2/eloquent#eager-loading.
So you query will be:
Product::with('store')
->where('category_id', $category->id)
->select(productFieldArray)
->paginate(20);

Laravel 4 unable to retrieve value from belongsTo relation using query builder

I have two tables, organizations and categories. This is how my tables and models are set up:
Tables:
organizations
id - integer
category_id - integer, fk
name - string
...
categories
id - integer
name - string
Models:
class Organization extends Eloquent
{
public function category()
{
return $this->belongsTo('Category');
}
public function comments()
{
return $this->morphMany('Comment', 'commentable');
}
}
class Category extends Eloquent
{
public $timestamps = false;
public function organization()
{
return $this->hasMany('Organization');
}
}
In my routes.php file, I have the following code (where $category is equal to "organizations"):
$query = Organization::query()
->join('categories', 'categories.id', '=', $category . '.id')
->select('categories.name as category');
$tiles = $query->get();
In my view, I am able to perform the following actions without any errors:
foreach($tile->comments as $comment)
{
...
}
...
$tile->name;
However, calling $tile->category->name will give me the error Trying to get property of non-object. And calling $tile->category will just return null. How can I display the category associated with the organization? I am able to retrieve other properties and relations just fine, but this is giving me a problem.
You have a bug in your code: $category . '.id' should be $category . '.category_id' doing so should make $tile->category->name work.
Also please note (you probably already know this) that in the code that you provided you are not actually using the belongsTo relation as set in your Organization class, you are just using the joined data.
The following would also work using the Eloquent ORM utilizing the models relationship methods:
$tiles = Organization::with('category')
->get();
foreach ($tiles as $tile)
{
echo $tile->name . '<br>';
echo $tile->category->name . '<br>';
}
Or you could do so the other way round from the categories model like so:
$tiles = Category::with('organization')
->get();
foreach ($tiles as $tile)
{
echo $tile->name . '<br>';
foreach($tile->organization as $org)
{
echo $org->name . '<br>';
}
}

Resources