j.code j.code - 5 months ago 23
Javascript Question

Creating a laravel txt with some data from database in LARAVEL

how can i create a method in laravel in my USER controller that when i click on a button in the view it will download a txt file with this info tha its generating from this query

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


Printing these 3 fields of Users table in 3 column in the txt file.
If someone can guide me doing this via jquery-ajax it would be perfect !

Answer
//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($data)];
        return \Response::make($txt , 200, $headers );

}