Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Secure and clean code in laravel 5.1

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 .

like image 959
Muhammad Atallah Avatar asked Mar 15 '23 07:03

Muhammad Atallah


1 Answers

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.

like image 144
closeneough Avatar answered Mar 31 '23 09:03

closeneough