2

This might be a duplicate, but i couldn't found any solution to my problem. I am retrieving few records from database and trying to display them in view. But always getting Undefined index: 0 Exception. Here's controller code:

public function gettopfirms(){
    $top = Top::all();
    foreach ($top as $tFirm) {
        $topFirms[] = Firm::whereId($tFirm['id'])->get()->toArray();
    }
    return view('top', compact('topFirms'));
}

And here's the view (top.blade.php) code:

<?php
    foreach ($topFirms as $firm) {
        echo "<pre>";
        print_r($firm[0]); //or $firm[0]['name']
        echo "</pre>";
    }
?>

And here's the Error:

Undefined offset: 0 (View: xxxxx/resources/views/top.blade.php)

Here is when i simply print array in view

Array
(
 [0] => Array
    (
        [id] => 7092
        [rank] => 147
        [name] => Grupo Grana y Montero (GyM),
     )

)
Array
(
 [0] => Array 
  (
     [id] => 2 //And So On

Don't know what's wrong am i doing, struggling and googling, didn't found a solution.

0

1 Answer 1

1

The problem is that you probably do not check if the array is set or not. So the solution should be like this i.e.:

<?php
    foreach ($topFirms as $firm) {
        if (!isset($firm[0])) {
            continue; 
        }

        echo "<pre>";
        print_r($firm[0]); //or $firm[0]['name']
        echo "</pre>";
    }
?>

You might also want to filter it out earlier so here:

public function gettopfirms(){
    $top = Top::all();
    foreach ($top as $tFirm) {
        $topFirms[] = Firm::whereId($tFirm['id'])->get()->toArray();
    }
    $topFirms = array_filter($topFirms);
    return view('top', compact('topFirms'));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.