Nothing bugs me more than code that does not look elegant. It is one of the reasons why I made the transition to laravel. Using laravel I can write my app efficiently and quite nicely. However, SQL in the form of the Eloquent Models or the Query Builder are still causing me eyesores.
Eloquent is good for single line queries:
$findUsername = User::find(Auth::id())->username;
But struggles to neatly represent more complicated queries.
Example 1:
$lobbyid = Request::get('lobbyid');
// I personally prefer single line variables for neatness
$checkOnline = UserLobbyInfo::select('id', 'online')->where([
['userid', '=', Auth::id()],
['lobby', '=', $lobbyid]
])->first();
if (count($checkOnline) && $checkOnline->online == "1") {
// if the user is online make sure you send a leave message
// we do not have to actually set online to 0 because we are removing the whole record
$this->send([ "lobby" => $lobbyid ])->leave();
}
Example 2:
return UserLobbyInfo::join('lobbies', 'lobbies.id', '=', 'user_lobby_info.lobby')
->select('user_lobby_info.userid',
'user_lobby_info.approved',
'user_lobby_info.invitedby',
'lobbies.id AS lobbyid',
'lobbies.title')
->where([
['user_lobby_info.userid', '=', Auth::id()],
['user_lobby_info.approved', '=', 2]
])
->orWhere(function ($query) {
$query->where('lobbies.owner', '=', Auth::id())
->where('user_lobby_info.approved', '=', 1);
})
->get();
This post might characterize me as overly picky or ocd but my intention is to write the best code that I possible can. This is a part of the learning curve. I simply would like a few stylistic ideas for improving the natural flow of these queries when included into my code code.
Things that I already have in mind:
you have to learn how to use many to many many to one relationships and try work with elequant is more easier than query builder