skip to Main Content

I am not able to show the name of the Hunter through the relationship between tables, it is returning the array of results.

This returns me

View reward of <?php echo e({"id":4, "name_hunter":"Gon Freecss"...})

I want to

View reward of Gon Freecss

HunterController.php

public function show($id)
{
    $rewarded = RewardedModel::find($id);
    $hunter = HunterModel::select('_id', 'name_hunter')->get();
    $reward = RewardModel::select('_id', 'description_reward')->get();
    return view('rewarded.view', compact(['rewarded', 'reward', 'hunter']));
}

view.php

@section('title', "View reward of {{ $rewarded->hunter->name_hunter }}")

How do I solve this?

2

Answers


  1. Any time you want a single result, use ->first(), not ->get().

    So, $hunter = HunterModel::select('_id', 'name_hunter')->get(); should be $hunter = HunterModel::select('_id', 'name_hunter')->first();, same for any other data.

    ->get returns a Collection of data (even if it found or got a single result), ->first will return an object (a model, but an Std in your case), so that will fix it.

    public function show($id)
    {
        $rewarded = RewardedModel::find($id);
        $hunter = HunterModel::select('_id', 'name_hunter')->first();
        $reward = RewardModel::select('_id', 'description_reward')->first();
    
        return view('rewarded.view', compact(['rewarded', 'reward', 'hunter']));
    }
    

    Read the documentation about ->first and ->get

    Login or Signup to reply.
  2. I think your usage of compact() is incorrect.

    Instead of:

    return view('rewarded.view', compact(['rewarded', 'reward', 'hunter']));
    

    Try this:

    return view('rewarded.view', compact('rewarded', 'reward', 'hunter'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search