0

Laravel by default asks for a DB called "laravel" and a users table called "users", but I named them in a different way and I want to make it works. Below the error it gives me:

public function store(Request $request)
{
    if ($request->hasFile('file'))
    {
        $file = $request->file('file');
        $name = time();
        $extension = $file->getClientOriginalExtension();
        $fileName = $name . '.' . $extension;
        $file->move(public_path('files/criticSuggestions'), $fileName);
    }
    SubCriticSuggestion::create([
        'user_id' => auth()->id(),
        'text' => $request->text,
        'critic_suggestion_id' => $request->critic_suggestion_id,
        'file' => $fileName
    ]);
    return redirect()->back();
}

I get this error

Undefined variable: fileName

  • You can update database name in .env file – mk23 Jul 01 '21 at 13:01
  • `$fileName` only exists if there is a file in the request. If the file is optional, initialize `$fileName` before your if check so that it exists even if there is no file. If the file is not optional, move your create statement inside of the if check. – aynber Jul 01 '21 at 13:14

1 Answers1

0

You most likely did not get inside the condition where the variable is declared $fileName

In add dd(). if it works, then everything is ok

if ($request->hasFile('file'))
    {
        dd('We here');

        $file = $request->file('file');
        $name = time();
        $extension = $file->getClientOriginalExtension();
        $fileName = $name . '.' . $extension;
        $file->move(public_path('files/criticSuggestions'), $fileName);
    }

In .env change db name

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=YOUR_DB_NAME
DB_USERNAME=root
DB_PASSWORD=root
Alex Black
  • 450
  • 2
  • 7
  • I put `dd` after `if`, but I see ` Undefined variable: fileName ` error again now, my problem did not solve yet. –  Jul 01 '21 at 13:10
  • @DeveloperLaravel Answer - You most likely did not get inside the condition where the variable is declared as $fileName. – Alex Black Jul 01 '21 at 13:12
  • @DeveloperLaravel you have to send post request with parameter file.check the name of your input. It should be = file – Alex Black Jul 01 '21 at 13:14