Home > Back-end >  Foreach on value blade Laravel
Foreach on value blade Laravel

Time:01-21

I have a problem with Laravel when I try to display my data via my view... Here is my code to browse everything with my view :

    @foreach($recipes as $t=>$d)
    {{$t}} // doesn't display all the key
    @endforeach
    
    {{$recipes->LABEL}} // work great

Their is the result : incrementing preventsLazyLoading exists wasRecentlyCreated timestamps

Their is my controller and the model :

Model : 
 /**
     * Get a recipe from its primary id : recipe_id
     * If fail it return 404 exception
     * Else return the collection with all the data of a recipe
     *
     * @param integer $id id of the recipe in the db
     * @return Collection the collection that have been finded by his id
     */
    public static function getRecipe($id)
    {
        return self::findOrFail($id);
    }

Controller : 

function getRecipe($id)
    {
        return view('recipe_detail')->with('recipes', Recipe::getRecipe($id));
    }

Is their any solution to display with foreach and with call the key ?

Thanks

CodePudding user response:

You have a single object $recipe that you are trying to loop on in your blade file.

This method:

 public static function getRecipe($id)
 {
     return self::findOrFail($id);
 }

returns the single object based on the $id. If you want a collection, skip the $id and use get() or all(), something like:

public function getRecipes(){
  return self::all()
}

Or, just call it right in the controller without need for the method in the Model: $recipes = Recipe::all();

You can then loop on $recipes in the blade file because it is now a collection.

CodePudding user response:

If you want to get all the "attributes" of the Model then you have to ask the Model for them; you can use the getAttributes method:

@foreach ($model->getAttributes() as $key => $value)
    ...
@endforeach
  •  Tags:  
  • Related