首页 > 解决方案 > 如何在 Laravel 中写入 .txt 文件?

问题描述

我想从数据库中获取 activationCode 的值,然后将其存储到 .txt 文件中。

这是我到目前为止所尝试的。

请帮忙!

注册控制器.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);

   }

标签: phpfileread-writelaravel-5.7

解决方案


您是否尝试过将对象转换为数组或字符串?确保您有权写入目标文件夹。使用它来帮助调试您的出路

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);
  }
}

推荐阅读