Skip to content
Advertisement

How to show specific order details and all products which belongs only to that specific order on same view

How to show specific order details and all products which belongs only to that specific order on same view? Trying this, but getting empty array when doing dd(). OrderController:

public function show(Order $order){
    $products = Product::where('order_id', $order);
    //dd($products);
    return view('order.view', ['order'=>$order, 'products'=>$products]);
}

web.php

    //Orders and products related routes
    Route::get('/order/{order}', 'OrderController@show')->name('order');
    Route::get('/orders/create', 'OrderController@create')->name('order.create');
    Route::post('/order', 'OrderController@store')->name('order.store');
    Route::get('/order', 'OrderController@index')->name('order.index');
    Route::delete('/order/{order}/destroy', 'OrderController@destroy')->name('order.destroy');
    Route::get('/order/{order}/edit', 'OrderController@edit')->name('order.edit');
    Route::put('/order/{order}/update', 'OrderController@update')->name('order.update');
 
    Route::get('/order/{order}/product/create', 'ProductController@create')->name('product.create');
    Route::post('/order/{order}/product', 'ProductController@store')->name('product.store');
 

Product.php

namespace App;
 
use IlluminateDatabaseEloquentModel;
 
class Product extends Model
{
    protected $guarded = [];
    
    public function order(){
        return $this->belongsTo(Order::class);
    }
}

Order.php

namespace App;
 
use IlluminateDatabaseEloquentModel;
use AppCustomer;
 
class Order extends Model
{
    protected $guarded = [];
    
    public function customer(){
        return $this->belongsTo(Customer::class);
    }
 
    public function products(){
        return $this->hasMany(Product::class);
    }
 
 
}

Advertisement

Answer

I would suggest to change the name of your route param to id to consistency and readability

Route::get('/order/{id}', 'OrderController@show')->name('order');

In view generate url for your route as

<a href="{{ route('order', [$id]) }}">Show Order</a>

And in controller you can get order details along with related products as

public function show($id){

    $order = Order::with('products')->find($id);
    
    return view('order.view', ['order'=>$order]);
}

And in view you can get collection of products from $order->products

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement