【问题标题】:Undefined method when trying to upload profile image尝试上传个人资料图片时未定义的方法
【发布时间】:2021-10-17 12:13:38
【问题描述】:

所以我尝试按照this 教程让我的用户能够上传个人资料图片。

但是在 HomeController 中最后的“更新”中给了我“未定义的方法”。

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

我已经尝试在上面“使用”Eloquent,以为是它的更新方法,但它仍然不起作用。

有什么我需要先调用它才能工作吗?

error printScreen

【问题讨论】:

  • 尝试 $user = User::find(auth()->id()); $user->update(['image'=>$filename]);或 $user = User::find(auth()->id()); $用户->图像=$文件名; $user->save();
  • 好的,现在它不会在更新时给出错误,而是在用户上给出:​​: Undefined type 'App\Http\Controllers\User'。
  • 你必须像使用 App\Models\User 一样导入用户模型;

标签: laravel image profile


【解决方案1】:

auth()->user() 返回一个 auth 外观实例但是 当你需要更新数据时,你需要一个 Model 实例,所以

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

【讨论】:

  • Auth facades 实例仅用于在登录用户表单会话中检索数据
  • 好的,现在它不会在更新时给出错误,而是在用户上给出:​​: Undefined type 'App\Http\Controllers\User'。
  • 控制器需要在顶部导入用户模型 使用 App/model/User 抱歉回复晚了
【解决方案2】:

在 routes/web.php 文件中添加这个...

使用 App\Http\Controllers\HomeController;

【讨论】:

  • Just did Still 给出同样的错误:(
  • 你能评论错误信息吗?
  • 使用它不会出错。它在可视代码中显示“未定义方法“更新”,就像我在“错误打印屏幕”中显示的那样
【解决方案3】:

正如用户@raghav 所说,使用 Auth->user() 为您提供了一个身份验证用户实例, 相反,您想使用 Auth id 从集合中查找用户,例如:

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

【讨论】:

  • 好的,现在它不会在更新时给出错误,而是在用户上给出:​​: Undefined type 'App\Http\Controllers\User'。
猜你喜欢
  • 2020-01-10
  • 2014-04-14
  • 2015-05-22
  • 1970-01-01
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
相关资源
最近更新 更多