【问题标题】:Class name problem on laravel 5.8 with Request->inputlaravel 5.8 上的类名问题与 Request->input
【发布时间】:2019-08-20 07:00:23
【问题描述】:

我正在尝试按照教程使用 Laravel 创建一个简单的网络爬虫here,但是 symfony 在第 49 行抛出了“类名必须是有效的对象或字符串”错误。在 phpstorm 中它确实给了我一个在 $website->title

上使用魔术方法访问的字段的轻微警告

我试图在我的 App/Website.php 中将 $title 声明为公共变量,但它仍然给了我这个错误。

这是错误代码的sn-p

    public function store(Request $request)
    {
        $this->validate($request,[
            'title'=>'required',
            'url'=>'required',
            'logo'=>'required'
        ]);

        $website = new Website();

        $website->title = new $request->input('title');

        $website->url = $request->input('url');

        $website->logo = $this->uploadFile('logo', public_path('uploads/'), $request)["filename"];

        $website->save();

        return redirect()->route('websites.index');
    }

    /**
     * Display the specified resource.
     *

这是我的应用程序/网站类:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Website extends Model
{
    protected $table = "website";
    public $title;
    /**
     * @var array|string|null
     */
    public $url;
    public $logo;

}

它应该已将标题、url 和徽标保存到我命名为 scraper 的 sql db 中,但它一直抛出此错误。请帮忙。

编辑 2:抱歉,我似乎复制了 symfony 显示的代码,我实际的 WebsiteController 是这样的再次复制了错误的代码,这是实际的实际代码:

public function store(Request $request)
    {
        $this->validate($request,[
            'title'=>'required',
            'url'=>'required',
            'logo'=>'required'
        ]);

        $website = new Website();

        $website->title = new $request->input('title');

        $website->url = $request->input('url');

        $website->logo = $this->uploadFile('logo', public_path('uploads/'), $request)["filename"];

        $website->save();

        return redirect()->route('websites.index');
    }

【问题讨论】:

  • 试试$website->title = $request->input('title')。不应有任何新的request 对象创建。
  • @Haru $website = 网站::find($id); $website->title = $request->input('title');是我的实际代码,上面是symfony显示的。
  • 您能相应地更新您的问题吗?
  • 相应更新。
  • 好。我会把它作为答案,但卡兰在我的评论之后做了一点。考虑给予他批准。该消息解释了您需要知道的一切。检查请求是否具有title 属性(或者它是否为空)。您可能想做的另一件事是在网站模型迁移中放置一个默认标题值(可能类似于$table->text('title')->nullable())。

标签: php laravel web-scraping homestead laravel-5.8


【解决方案1】:

这里 new 不应该在那里,$website->title = new $request->input('title'); ,您没有从任何类中制作对象。我猜你想念类型。

您仍然可以通过 $request->title; 获取您的数据,我更喜欢这个,因为它缩短了您的代码并且仍然可读。

像下面那样做

$website->title = $request->input('title');

或者

$website->title = $request->title; 并且还可以将数据保存到数据库中,您不需要声明变量。

只需在模型中添加受保护的$fillable=['title','url','logo'];

或者如果您使用save() 方法,您甚至不需要添加$fillable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 2012-04-23
    相关资源
    最近更新 更多