Split string in Laravel Framework

≡放荡痞女 提交于 2020-05-15 07:30:08

问题


How do I split string and display it in a table in Laravel Framework? I fetch data from my database that consists of one column but in a string such as { 1234, normal, r4r3r2 }. I want to split it into three different parts/values by commas and display it in a table of three columns.

For now, I only can display the data without splitting the them.

My HomeController:

public function index()
  {
    $test = Test::all();
    return view('home')->with('test', $test);
  }

My home.blade.php:

<ol>
   @foreach($test as $row)
     <li>{{ $row->data }}</li>
   @endforeach
</ol>

回答1:


First explode the $test variable to get Array,

<ol>
 @foreach(explode(',',$test) as $row)
  <li>{{ $row }}</li>
 @endforeach
</ol>

After explode using foreach single key we can access from the array. I hope it helps.




回答2:


You can explode you string in blade file like this

@foreach(explode(',', $row->data) as $fields) 
    <li>{{$fields}}</li>
@endforeach

And using of your model you can also done like this

class Test extends Model 
{
  public function getDataAttribute()
  {
    return explode(',', $this->data);
  }
}

it's return your data explode with comma separated array.



来源:https://stackoverflow.com/questions/47068362/split-string-in-laravel-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!