Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode string in laravel blade template

I'm new for laravel framework. I want to explode string and run foreach loop. Here is my code, assume $data->facing="Hello,World";

@if ($data->facing != "")
@foreach($data->facings as $info)
<option>{{$info}}</option>
@endforeach
@endif

how to explode $data->facing using ",".

like image 796
saravanan mp Avatar asked Dec 07 '15 04:12

saravanan mp


3 Answers

Just simply explode, however this logic should come from your controller/model

@if ($data->facings != "")
  @foreach(explode(',', $data->facings) as $info) 
    <option>{{$info}}</option>
  @endforeach
@endif

If $data is some sort of model, I would suggest adding an accessor to your model

class MyModel extends Model 
{
  public function getFacingsAttribute()
  {
    return explode(',', $this->facings);
  }
}

Then you can simply treat it as an array, as per your original example.

@foreach($data->facings as $info)
like image 54
Ben Rowe Avatar answered Oct 22 '22 21:10

Ben Rowe


Use explode like this:

$new_array = array();
if($data->facing) { 
$new_array = explode(',',$data->facing);
}
@if (is_array($new_array) && count($new_array) > 0)
@foreach($new_array as $info)
<option>{{$info}}</option>
@endforeach
@endif
like image 44
Maha Dev Avatar answered Oct 22 '22 19:10

Maha Dev


Blades @foreach directive is just a wrapper around PHPs native foreach:

@foreach(explode(',', $data->facings) as $info)
    <option>{{ $info }}</option>
@endforeach
like image 30
tommy Avatar answered Oct 22 '22 19:10

tommy