phplaravellaravel-4

fatal error class name must be a valid object or a string


I'am new to laravel and php , I have this function in my controller , it gives me that error fatal error class name must be a valid object or a string

public function getIndex () {
    $categories = array();

    foreach ( $Category::all() as $key=> $category) {
        $categories[$category->id] = $category->name ;
    }

and this is my whole controller

<?php 

class ProductsController extends BaseController {



public function __construct(){

    $this->beforeFilter('csrf' , array('on'=>'post')) ;
 }

public function getIndex () {
    $categories = array();

    foreach ( $Category::all() as $key=> $category) {
        $categories[$category->id] = $category->name ;
    }


    return View::make('products.index')
    ->with('products' , Product::all())
    ->with('categories' , $categories);
 }

public function postCreate(){

    $validator = Validator::make(Input::all() , Product::$rules);

    if ($validator->passes()){
        $product = new Product ; 
        $product->category_id = Input::get('category_id');
        $product->title = Input::get('title');
        $product->description = Input::get('description');
        $product->price = Input::get('price');

        $image = Input::file('image');
        $filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
        Image::make($image->getRealPath())->resize(468,249)->save('public/img/products/'.$filename);
        $product->image = 'img/products/'.$filename;
        $product->save(); 

        return Redirect::to('admin/products/index')
        ->with('message' , 'Product Created');


    }
    return Redirect::to('admin/products/index')
    ->with('message', 'Something went wrong')
    ->withErrors($validator)
    ->withInput() ;
    }

public function postDestroy(){

        $product = Product::find(Input::get('id'));

        if($product){
            File::delete('public/'.$product->image);
            $product->delete() ;
            return Redirect::to('admin/products/index')
            ->with('message' , 'Product Deleted');

        }
        return Redirect::to('admin/products/index')
            ->with('message' , 'Something went wrong');


     }

    public function postToggleAvailability(){
        $product = Product::find(Input::get('id'));
        if($product){
            $product->availability = Input::get('availability');
            $product->save();
            return Redirect::to('admin/product/index')->with('message', 'product updated');

        }
        return Redirect::to('admin/product/index')->with('message' , 'Invalid Product');

    }


}

Solution

  • Assuming the class is called Category you should use Category::all() in the foreach. Making: $categories = array();

    foreach ( Category::all() as $key=> $category) {
        $categories[$category->id] = $category->name ;
    }