1

New to Laravel. I am trying to use a controller to services that match what is sent in the URL.

Sample URL:

/public/service/cost/2

The Code in the Controller is:

public function getServiceCost($id) {

    $service = Service::whereIn('id', array($id))->get();

    return $service;
}

I want to be able to pass multiple ids in the URL like so: /public/service/cost/1,2,3

If I hard-code to test, it works fine.

public function getServiceCost($id) {
  $service = Service::whereIn('id', array(1, 2, 3))->get();
  return $service;
}  

What do I need to do to pass the arguments from the URL into the whereIn so that it returns what I pass in the URL?

If I use

/public/service/cost/2,3

It only returns the data for id 2.

I changed the function to use Request $request, but it still only shows one result:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Service;

class ServiceController extends Controller
{ 
    public function getServiceCost2(Request $request) {
        $service = Service::whereIn('id', array($request->get('id')))->get();

        return $service;
    }
}

URL used was:

public/service/cost?id=1,2
BillyB
  • 28
  • 5
  • I suggest you check how to pass an array via query string https://stackoverflow.com/questions/6243051/how-to-pass-an-array-within-a-query-string – dhinchliff Jan 22 '18 at 20:24

3 Answers3

1

Hi @BillyB you need to rethink your URL Structure, you can pass multiple parameters using GET Parameters.

I would recommend you to create service URL:

/public/service/cost?id[]=1&id[]=2&id[]=3

The Code in the Controller is:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

.....

public function getServiceCost(Request $request) {

    $service = Service::whereIn('id',$request->get('id'))->get();

    return $service;
}

Its well documented at https://laravel.com/docs/5.3/requests

Ersin Demirtas
  • 666
  • 6
  • 14
0

I think that you need to change your route method passing to POST, and your form will make a name like this, for example:

<input type="text" name="id[]" />

And doing this way, you can catch in your controller an array with multiple ids, using:

request()->get('id');
-2

Try use:

$arr = explode(',',$id)

They u will have a array with ids

Kuba Zabielski
  • 146
  • 2
  • 10