1

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 !

Axel
  • 73
  • 1
  • 11
  • Don't do a foreach, it's just `$expertCategory["id"]`. It is a single category you are getting after all. – apokryfos Jul 04 '17 at 08:05
  • Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – LF00 Jul 04 '17 at 08:06
  • thank you sir, thats really work, and just realize that my query use "first()" thats why when using for each will get error. thank you for ur help ! god bless! – Axel Jul 04 '17 at 08:14

1 Answers1

1

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.

Bibhudatta Sahoo
  • 4,808
  • 2
  • 27
  • 51
  • thank you sir Sahoo, just realize that my query select with "first()" only thats why i can't use for each . thank you for ur help sir ! – Axel Jul 04 '17 at 08:16
  • @Axel you are welcome if your issue solved then just close your question by accepting my answer.Thank you :) – Bibhudatta Sahoo Jul 04 '17 at 08:18