Home > Enterprise >  Undefined method when trying to upload profile image
Undefined method when trying to upload profile image

Time:10-18

So I'm trying to follow this tutorial to make my users been able to upload a profile picture.

But in the HomeController is giving me "undifined method" in the final "update".

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use App\Models\Flight;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('home');
    }

    public function upload(Request $request)
    {
        if($request->hasFile('image')){
            $filename = $request->image->getClientOriginalName();
            $request->image->storeAs('images',$filename,'public');
            Auth()->user()->update(['image'=>$filename]);
        }
        return redirect()->back();
    }
}

I already tried to 'use' Eloquent above, thinking it was the update method from it, but it still doesn't work.

Is there something that i need to call first for it to work?

error printScreen

CodePudding user response:

auth()->user() return a auth facade instanc but when you need to update data you need a Model instance so

$userData = user::find(auth()->user()->id);
$userData->image = $filename;
$userData.save()

CodePudding user response:

Add this in routes/web.php file...

use App\Http\Controllers\HomeController;

CodePudding user response:

as user @raghav said, using Auth->user() gives you an auth user instance, instead you want to find a user from the collection by using the Auth id, ex :

$userData = User::find(auth()->id);
$userData->image = $filename;
$userData->save();
  • Related