How to write to a .txt file in Laravel?

Shamima Saleem picture Shamima Saleem · Oct 23, 2018 · Viewed 18.2k times · Source

I want to get the value of activationCode from database and then store it into a .txt file.

This is what I tried to so far.

Please help!

registerController.php

  protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'],
            'password' => bcrypt($data['password']),
            'activationCode' => rand(1000,9999),
        ]);


     }


     public function put() {

         $user = User::where('is_active', 0)->get();

          $file = Storage::put( 'myfile.txt', $user);

   }

Answer

abr picture abr · Oct 23, 2018

Have you tried converting the object to an array or a string? Make sure you have permissions to write in th destination folder. Use this to help debug your way out

public function put() {
   try {
       $attemptToWriteObject = User::where('is_active', 0)->get();
       $attemptToWriteArray = User::where('is_active', 0)->get()->toArray();
       $attemptToWriteText = "Hi";
   
       Storage::put('attempt1.txt', $attemptToWriteObject);
       Storage::put('attempt2.txt', $attemptToWriteArray);
       Storage::put('attempt3.txt', $attemptToWriteText);
  } catch (\Exception $e) {
       dd($e);
  }
}