Vranvs
Vranvs

Reputation: 1531

Using Resource Routes in Laravel

I have what I think is probably a pretty simple question.

I generated a resource route for my class 'Orders', as they will need to be created, destroyed, edited, viewed, etc.

I have a spot in my app where I want to load all orders via AJAX which are currently 'outstanding' (!= finished).

I think I'm supposed to use the orders.show route for this, yes? My only confusion comes in the URI whereby it says to access the orders.show route, you need to specify an order, like so:

order/{order}

enter image description here

If I want to use AJAX to talk to my controller such that the controller returns a list of orders that it grabs from the database where status != completed, what do I specify in the URI? I don't want to grab ONE order, I want to grab SEVERAL.

From my controller:

  public function show(Order $order){
    $orders = Order::where('status', '!=' , 'Received')->get();
    return $orders;
  }

Thanks so much.

Upvotes: 0

Views: 589

Answers (1)

Dwight
Dwight

Reputation: 12470

The show method is when you're returning a single resource - a single order. That's why it takes a reference to the order as part of the route.

The index method is the one that returns a collection of a resource - multiple orders. You can go about this a number of ways: you could have a regular OrdersController that returns all orders by default, but a query parameter might restrict is base on status, or you could create a specific OutstandingOrdersController which returns just those orders.

Here's an example of how you might go about it the first way.

class OrdersController extends Controller
{
    public function index()
    {
        $orders = Order::query();

        if (request()->has('outstanding')) {
            $orders->where('status', '!=', 'Received');
        }

        return $orders->get();
    }
}

Then, your Ajax library can do GET /orders for all orders, or GET /orders?outstanding to only retrieve outstanding orders. You might also consider taking a status parameter to the query to only retrieve orders of a certain status.

Upvotes: 2

Related Questions