How to get order relation in laravel - laravel

I have 1 relation
Order(id, user_id, total_price)
OrderDetail(order_id, product_id, num_of_product)
Product(id, title, num_of_existed, price)
Ask: How to get order across template:
order:[
id: 1,
user_id:1,
total_price:1.1,
order_detail:[
id:1,
order_id:1,
book_id:1,
num_of_product:10
product:[
id:1,
title: 'abc',
num_of_existed: 100,
price: 0.1
]
]
]

Create relationship in your Order model as ,
public function order_details()
{
return $this->hasOne('App\OrderDetail','order_id','id');
}
In your Orderdetail model,
public function product_details()
{
return $this->belongsTo('App\Product','id','product_id'); // first foreign key then local key
}
In your controller
$orders = Order::all();
return view('view_name',compact('orders'));
In the view
#foreach ($orders as $order)
#if ($order->order_details)
{{$order->order_details->num_of_product}}
#if($order->order_details->product_details)
{{$order->order_details->product_details->title}}
{{$order->order_details->product_details->num_of_existed}}
{{$order->order_details->product_details->price}}
#endif
#endif
#endforeach

you can do it via laravel eloquent relationship, to define relationship you will have 3 models like Order, OrderDetail,Product related to corresponding tables.
On your order model:
public function OrderDetail()
{
return $this->hasOne('App\OrderDetail','order_id');
}
On your OrderDetail model:
public function Order()
{
return $this->belongsTo('App\Order','order_id');
}
public function Product()
{
return $this->belongsTo('App\Product','product_id');
}
Then on your controller
public function foo(){
$orders=Order::all(); //remember to use 'App\Order'
return view('filename',compact('orders'));
}
Now on your blade, you will find all related table data just by chaining orders
#foreach ($orders as $order)
#if ($order->OrderDetail)
#if($order->OrderDetail->Product)
{{$order->OrderDetail->Product->title}}
#endif
#endif
#endforeach
for more see documentation

Related

Laravel fetch intermediate table data with many to many relationship

I have 3 tables
user, specialities & results
results contain specialitie_id, user_id
I have create many-to-many relationship
Here's the relationship in user model
public function specialities()
{
return $this->belongsToMany(Speciality::class, 'results', 'user_id', 'specialitie_id')->withPivot('result', 'color');
}
I want to fetch data from the result table based on specialitie_id
If my url is
abc.com/result/5
I have attached table structure as well,
it should show me result related to specialitie_id 5
I tried this but it doesn't work
$result = User::with('specialities')->where('id', 5)->get();
Any help would be appreciated.
Your current query:
$result = User::with('specialities')->where('id', 5)->get();
Is saying, give me all results where the USER_ID = 5 WITH all the specialities related to it.
You are very close but did it backwards:
//Give me all results where the SPECIALITY_ID = 5
//WITH all the users related to it
$result = Speciality::with('users')->where('id', 5)->get();
Please note that the above is an array
Example of a Controller Function:
public function results($id){
$results = Speciality::with('users')->where('id', $id)->get();
return view('user_specialities', compact('results'));
}
Example view user_specialities:
#foreach($results as $result)
<p>Result: {{$result->result}}</p>
<p>Formulary: {{$result->formulary}}</p>
<p>Color: {{$result->color}}</p>
<p>User ID: {{$result->user->id}}</p>
<p>User Name: {{$result->user->name}}</p>
#endforeach
Speciality Model:
public function users()
{
return $this->belongsToMany(User::class, 'results', 'specialitie_id', 'user_id')->withPivot('result', 'color');
}
User Model:
public function specialities()
{
return $this->belongsToMany(Speciality::class, 'results', 'user_id', 'specialitie_id')->withPivot('result', 'color');
}

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 Eloquent "With" and sub "With" relationship query -> pass Column Value as Where clause

I have 3 Models "Category" (tableName = 'categories'), "Brand" ('brands'), "Item" ('items')
Can I pass parent column value (e.g. categories) to use it in the Where clause?
Simple example:
Category::with(['brands' => function ($q) {
$q->with(['items' => function ($query) use ($localWhereHas) {
$query->whereColumn('category_id', 'categories.id');
}]);
}]);
Relations are:
Category Model:
public function brands(): BelongsToMany
{
return $this->belongsToMany(Brand::class, 'category_brands')->withPivot('is_visible', 'addon_price');
}
Brand Model:
public function items(): HasMany
{
return $this->hasMany(Item::class, 'brand_id');
}
Item Model:
public function category(): BelongsTo
{
return $this->belongsTo(Category::class, "category_id");
}
The main idea is that I need the structure to be nested like this Category->Brands->Items
The backup plan is to fetch All needed Categories and Foreach them to get as many as categories I have all Brands->Items, using categoryId ($category->category_id) .... but I don't like it
No, you can't pass it directly because it is not the same context.
If you want to have a display like this :
Category
-brand
-item
Then you should maybe just group your items by brand :
$categories = Category::with('items.brand')->get();
#foreach($categories as $category)
{{ $category->name}}
#foreach($category->items->groupBy('brand_id') as $brand_id => $items)
{{ $items->first()->brand->name }}
#foreach($items as $item)
{{ $item->name }}
#endforeach
#endforeach
#endforeach

How to fetch all data from 3 tables with condition in laravel?

I have 3 tables school ,schooldetails & admission, and i want to get all data in index page how can i do that , i am getting data of school and admission table due to relationship but not of school details kindly check it and help
school
id
name
name
mobile
city
schooldetails
id
school_id(foreign key of school id)
contact_person
admission
id
school_id(foreign key of school_deatils id)
admission_classes
start_date
end_date
My function
public function schoolslist($class='', $city='')
{
$schools = Admission::where('admission_classes', 'like', "%{$class}%")->where('status', '1')->orderBy('id','desc')->whereHas('school', function($query) use($city) {
$query->where('city', 'like', $city);
})->paginate(10);
return view('frontend.index',compact('schools'));
}
my Admission model
public function School()
{
return $this->belongsTo('App\School');
}
public function SchoolDetails()
{
return $this->belongsTo('App\SchoolDetails');
}
My view
#foreach($schools as $i => $school)
{{ $school->School->name}} from user table Ravi
{{ $school->SchoolDetails->contact_person}} //from school_Details table No result
{{ $school->start_date }} //from admission table date 11/22/2018
#enforeach
SchoolDetails relation should be with school not addmission so remove SchoolDetails() from Admission Model and add it to School Model
School Model:
public function Admission()
{
return $this->hasMany('App\Admission');
}
public function SchoolDetails()
{
return $this->hasOne('App\SchoolDetails'); \\Edited
}
Admission model:
public function School()
{
return $this->belongsTo('App\School');
}
SchoolDetails model:
public function School()
{
return $this->belongsTo('App\School'); \\Edited
}
Then you can change your View accordingly:
#foreach($schools as $i => $school)
{{ $school->School->name}} from user table Ravi
{{ $school->School->SchoolDetails->contact_person}} // This Line is changed
{{ $school->start_date }}
#enforeach

How to best get results from 3 different tables based on ID matches in Laravel.

Trying to get products AND variants for a particular supplier.
I can get the products easy enough, but can't figure out how to best get to the variants with matching product_id and send it to the view.
Variants.product_id matches with Product.ID
This works (getting products for the supplier)
public function suppliers($id) {
$supplier = Supplier::orderby('company_name', 'ASC')->find($id);
$products = Supplier::find($id)->products;
$data = [];
$data['supplier'] = $supplier;
$data['products'] = $products;
return view('admin.purchasing.supplier-details', $data);
}
I've tried this to get the variants also without luck.
Controller:
public function suppliers($id) {
$supplier = Supplier::orderby('company_name', 'ASC')->find($id);
$products = Supplier::find($id)->products;
$variants = array();
foreach ($products as $product) {
$product_id = $product->id;
$variants[] = Variant::find($product_id);
}
$data = [];
$data['supplier'] = $supplier;
$data['products'] = $products;
$data['variants'] = $variants;
return view('admin.purchasing.supplier-details', $data);
}
View:
#foreach($products as $product)
<tr>
<td>{{ $product['title'] }}</td>
#foreach($variants as $variant)
#if($variant->product_id == $product['id'])
<td>${{ $variant->price }}</td>
#else
<td>not set</td>
#endif
#endforeach
</tr>
#endforeach
Any tips much appreciated.
First of all , you should have relation set on your models to make this work
like this For exemple :
Supplier.php
public function products()
{
return $this->hasMany('App\Product');
}
Product.php
public function variants()
{
return $this->hasMany('App\Variant');
}
public function Supplier()
{
return $this->belongsToMany('App\Supplier'); //in case you have only one supplier for each product change this to belongsto
}
Variant.php
public function products()
{
return $this->belongsToMany('App\Product'); //not sure if this should be manytomany or one to many , it deppends on what you did
}
anyway now you can do this
Controller
public function suppliers($id) {
$Data = Supplier::where('id',$id)->orderby('company_name', 'ASC')->with('products.variants')->first(); //you will get the supplier with all products associated to him with variants foreach product
return view('admin.purchasing.supplier-details')->with('Data',$Data); // now you just loop the $supplierwithproducts->products to get results (dd the variable to check output)
}
View
{{ $Data->name }} // supplier name since Supplier model was the starting point
#foreach($Data->products as $product) //loop all products related to that supplier
{{ $product->name }} //shows product name (depends on you database columns
#foreach($product->variants as $variant) // loops all variants in the current product
{{ $variant->name }} // shows variants
#endforeach
#endforeach
If you copy and paste this code it might not work ,but this will give you an idea how you should handle relations in laravel (levrage eloquent relations)
Check this for more informations
Laravel Docs
Laracasts Defining Relationships With Eloquent
Laracasts Updating Records and Eager Loading

Resources