使用LARAVEL中的数据库中的一些数据创建laravel txt

时间:2016-06-28 12:31:50

标签: php jquery json laravel

如何在我的USER控制器中创建一个laravel方法,当我点击视图中的按钮时,它将下载一个带有此信息的txt文件,该信息由此查询生成

User::select('id','name','lastname')
            ->orderBy('id','desc')
            ->take(100)
            ->get();

在txt文件的3列中打印Users表的这3个字段。 如果有人可以通过 jquery-ajax 指导我这样做,那将是完美的!

更新感谢下面的家伙解决了我的问题!

1 个答案:

答案 0 :(得分:2)

//controller

public function downloadTxt()
{
  $txt = "";
  $datas = User::select('id','name','lastname')
            ->orderBy('id','desc')
            ->take(100)
            ->get();
  foreach($datas as $data){
  $txt .= $data['id'].'|'.$data['name'].'|'.$data['lastname'].PHP_EOL;
  }
  $txtname = 'mytxt.txt';
     $headers = ['Content-type'=>'text/plain', 'test'=>'YoYo', 'Content-Disposition'=>sprintf('attachment; filename="%s"', $txtname),'X-BooYAH'=>'WorkyWorky','Content-Length'=>sizeof($datas)];
        return \Response::make($txt , 200, $headers );

}