Ad

Laravel5 Controller Issue. Undefined Variable: Filename

I want to upload a blogger's profile image but I get an error:

Undefined variable: file_name.

I think it is a controller issue. I don't know why the variable is not defined, though I declared the same variable name. I restarted the server but it did not work.

So please help me out.

BloggerController.php

public function store(Request $request, User $user_id)
{
    $user_id = DB::table('users')->where('id', $user_id)->get();

    if ($request->hasfile('image')) {
        $file = $request->file('image');
        $ext = $file->getClientOriginalExtension();
        $file_name = time() . '.' . $ext;
        $file->move('bloggers/', $file_name);
    }

    $blog = Blog::create(
        ['user_id' => $user_id],
        [
            'image'        => $file_name,
            'introduction' => $request->introduction,
        ]
    );

    return redirect(route('blogger'));
}

I also changed the store method.

if ($request->hasfile('image')) {
    $file_name = $request->file('image')->getClientOriginalName();
    $request->file('image')->storeAs('bloggers/', $file_name);
}

My migration

Schema::create('blogs', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('bloggers');
    $table->string('image');
    $table->string('introduction');
    $table->timestamps();
});

error image

Ad

Answer

To be sure that your variable $fillename is available then change your code to this

if($request->hasfile('image')){
      $file = $request->file('image');
      $ext = $file->getClientOriginalExtension();
      $filename = time().'.'.$ext;
      $file->move('bloggers/', $filename);

      $blog = Blog::create(
            ['user_id' => $user_id],
            [
                'image'=>$filename,
                'introduction' => $request->introduction,
            ]
        );
}
Ad
source: stackoverflow.com
Ad