Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

knoedelauflauf's avatar

view without data control

hey all,

my actual situation. controller:

public function show($id)
    {
        $account = Account::with('characters')->find($id);
        return view('accounts.show')->with('account', $account);
    }

view:

    <p>
      @if ($account->user != NULL)
          Email: {{$account->user->name}}@example.com
      @else
          no User assigned
      @endif
    </p>   
<td>UK</td>
            @for ($i=2;$i<=4;$i++)
            <td>
              @if ($account->characters->where('server',$i)->where('country',"UK")->first() != NULL)
                {{$account->characters->where('server',$i)->where('country',"UK")->first()->charid}}
              @endif
            </td>
            @endfor
        </tr>

I have got three tables, users, accounts, characters, with a 1 on 1 relation between users,accounts(foreign key) and a 1 to many between accounts,characters(foreign key). I am looking for a better way as it seems that it runs quite a lot database querys. In addition it is not really convenient to use 'if-clauses' in the view. i tried as followed:

$account = DB::table('accounts as a')->where('a.id',$id)->join('characters as c', 'c.account_id', '=','a.id')->select('a.accid as accid', 'c.charid as charid', 'c.server as server', 'c.country as country')->get();

but now i am missing the username and I still need to control if the character exists, as there is not always a character on the server.

Thank you in advance.

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

you should eager load the user as well as characters

in your view, you can lose the @if by using or or the null coalesce operator ?? in php 7

i can't really fathom what you are doing in that loop and running where filter in the loop so can't really advise further

1 like
knoedelauflauf's avatar

Thank you, I'm eager loading the users now as well.

I have got 3 servers and 4 countrys. I am going to create a Table with the countrys as row and the server as column, there can be only one character on each (server|country) tuple and if there is a character I need to display the charid, if not the field should be empty. Each character is unique with [server, charid]. hopefully this informations can be usefull.

Please or to participate in this conversation.