skip to Main Content
 "message": "Call to a member function find() on array",
    "exception": "Symfony\Component\Debug\Exception\FatalThrowableError",

How do I get the id parameter from the array below: When i pass the parameter 1 i want to fetch only first element when id is 2 I fetch item 2 of array

  public function payments($id){
        $data = [
            ['id' => 1, 'amount' => '22000', 'name' => 'ken'],
            ['id' => 2, 'amount' => '24000', 'name' => 'ken'],
            ['id' => 3, 'amount' => '26000', 'name' => 'ken'],
            ['id' => 4, 'amount' => '2000', 'name' => 'tom'],
        ];

        return $data->find($id);
    }

3

Answers


  1. Chosen as BEST ANSWER
    public function payments($id){
        $data = [
            ['id' => 1, 'amount' => '22000', 'name' => 'ken'],
            ['id' => 2, 'amount' => '24000', 'name' => 'ken'],
            ['id' => 3, 'amount' => '26000', 'name' => 'ken'],
            ['id' => 4, 'amount' => '2000', 'name' => 'tom'],
        ];
        $data = collect($data);
        return $data->where('id', $id)->all();
    }
    

  2. Since we’re using a multi-dimensional array, we can use array_search with array_column.

    $data = [
        ['id' => 1, 'amount' => '22000', 'name' => 'ken'],
        ['id' => 2, 'amount' => '24000', 'name' => 'ken'],
        ['id' => 3, 'amount' => '26000', 'name' => 'ken'],
        ['id' => 4, 'amount' => '2000', 'name' => 'tom'],
    ];
            
    $key = array_search($id, array_column($data, 'id'));
    echo var_dump($data[$key]);
    
    Login or Signup to reply.
  3. If you want a "Laravel" alternative solution using collection

    public function payments($id){
        $data = [
            ['id' => 1, 'amount' => '22000', 'name' => 'ken'],
            ['id' => 2, 'amount' => '24000', 'name' => 'ken'],
            ['id' => 3, 'amount' => '26000', 'name' => 'ken'],
            ['id' => 4, 'amount' => '2000', 'name' => 'tom'],
        ];
        $data = collect($data);
        return $data->where('id', $id)->first();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search