code Concept
code Concept

Reputation: 31

ErrorException (E_NOTICE) Undefined offset: 0 laravel

I am trying to read from the database and display data into a form but I Keep getting this error.

This is my controller:

public function create()
{
    /* this function gets data from the database (marks table) and render it to the view view */

    $data['data']=DB::table('marks')->get();

    if(count($data[0])>0){
        return view('view',$data);
    }
    else{
        return view('view');
    }   
}

And this is how I have defined the route:

Route::resource('claude', 'viewcontroller');

Upvotes: 0

Views: 5982

Answers (3)

Hello Hack
Hello Hack

Reputation: 109

 if(is_array($data) && isset($data)){
     return view('view',$data);
 }

Upvotes: 0

Thijs
Thijs

Reputation: 1012

get() will return a collection, you can check if its has items by

    if ($data['data']->count()) {

        return view('view',$data);
    } else {
        return view('view');
    }

Upvotes: 0

Tharaka Dilshan
Tharaka Dilshan

Reputation: 4499

The variable $data doesn't have an index of 0.
But it has a key called data.
So you have to access it via the key.

It should be

 if(count($data['data']) > 0){
     return view('view',$data);
 }

Upvotes: 4

Related Questions