You would take a look at View Models
https://laracasts.com/series/whip-monstrous-code-into-shape/episodes/11
and
https://laravel-news.com/laravel-view-models
Nov 15, 2018
2
Level 14
How to avoid mixing PHP code in View and vice versa?
I am learning to write better code and to not mix PHP code with HTML/CSS since that will be better both for me and people who will read my code after me. However I stumbled upon a situation where I have users with different roles and each role has it's own color/class/style/html. I end up putting either HTML code in my PHP logic or vice versa. Is there a nice way around this?
In Controller:
if ($user_role == 'administrator') {
$user_color == '#ff0000'; <-- CSS Style in my PHP
$user_class == 'admin-class'; <-- CSS Class in my PHP
}
$users = [
'username' => 'John',
'user_color' => '#ff0000' <-- CSS Style in my PHP
]
In my View:
<a class="{{ $user_class }} style="color: {{ $user_color }}">Administrator</a>
or if I did not want HTML or CSS in my PHP then I end up putting PHP in my HTML.
In my View:
foreach($users as $user):
// Too much PHP logic in my HTML view
if ($user->role == 'administrator') {
$user_color = 'red';
} else if ($user->role == moderator) {
$user_color = '#00ff00'
}
<a style="color: {{ $user_color }}">{{ $user->username }}</a>
endforeach;
So either way, I end up mixing the two together. This is just one example where I need to adjust the HTML depending on some logic or conditions.
Please or to participate in this conversation.