In fact i have a question about the clean of code
i try to get some value in blade file , I Am confused between two approaches
i think both are right but i need to know who's clean and secure more with the reason
First approach in my blade directly using Eloquent
@foreach
(Auth::user()->company->country->cities as $city) {{$city->name}}
@endforeach
Second approach using Injecting Services by create this method in my model and use it in my blade using laravel 5.1 Injecting Services
public function getCity()
{
foreach(Auth::user()->company->country->cities as $city) {
return $city->name ;
// OR
return $city ;
// i think this is one of benefits to use this approach
// because in my view i can use getCity()->id or getCity()->name
}
}
Thanks For Your Time .
Your second approach wouldn't work, because the function will finish while returning the name of the first city (or the first city itself). To make it work you could rewrite it, so that it returns all cities and loop through them in blade.
So if you use that function your code might look like:
@foreach($serviceName->getCities() as $city)
{{ $city->name }}
@endforeach
which is a nice thing, because the view doesn't have to care about where the cities will come from. If you use such a service on different views, it will be much easier to update.
Regarding security: There is no difference between those two approaches. As long as you print your output using the '{{ }}' operator. It'll prevent possible XSS attacks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With