Axel
Axel

Reputation: 83

Illegal String offset & Trying to get property of non-object (laravel 5.3)

So i've problem to print the result in blade that the data are from controller, so :

  1. UseController.php :

         $expertCategory = Category::getCategoryByID($user_id);
         $data = [ 'expertCategory' => $expertCategory ];
         return view('cms.user.edit', $data);
    
  2. Category.php (models) getCategoryByID($user_id) return result array if i dd(expertCategory); in controller, which the result is :

    array:9 [▼
       "id" => 1
       "name" => "Beauty"
       "sequence" => 1
       "background_color" => "ffffff"
       "status" => "Active"
       "created_at" => "2017-06-19 09:41:38"
       "updated_at" => "2017-06-19 09:41:38"
       "icon_filename" => "beauty-icon"
       "iconURL" => array:3 [▼
                "small" => "http://localhost:8000/images/category_icons/small/beauty-icon"
               "medium" => "http://localhost:8000/images/category_icons/medium/beauty-icon"
         ]
    ]
    
  3. But when i want to print using foreach the result in blade.php with code :

     @foreach($expertCategory as $expertCat)
       {{ $expertCat->id }}
     @endforeach
    

will return error "Trying to get property of non-object "

if i use code like this :

@foreach($expertCategory as $expertCat) {{ $expertCat['id'] }} @endforeach

it will return : "Illegal string offset 'id'"

anybody can help solve this problem :s ? many thanks !

Upvotes: 1

Views: 908

Answers (1)

Bibhudatta Sahoo
Bibhudatta Sahoo

Reputation: 4894

As $expertCategory is a one dimensional array you are facing this issue

Just Replace this

$expertCategory = Category::getCategoryByID($user_id);
$data = [ 'expertCategory' => $expertCategory ];
return view('cms.user.edit', $data);

With

$expertCategory = Category::getCategoryByID($user_id);
$data = [ 'expertCategory' => [$expertCategory] ];
return view('cms.user.edit', $data);

Then use

@foreach($expertCategory as $expertCat)
  {{ $expertCat['id'] }}
@endforeach

In your blade it will work for you.

Upvotes: 1

Related Questions