【问题标题】:Call to a member function error in Laravel在 Laravel 中调用成员函数错误
【发布时间】:2020-09-30 05:35:55
【问题描述】:

我正在 Laravel 7 上构建博客,当我尝试创建帖子时出现此错误:

Call to a member function categories() on bool

这是我的控制器中的存储方法:

public function store(Request $request)
    {
        // Validate incoming data
        $this->validate($request, [
            'title' => 'required',
            'image' => 'required',
            'categories' => 'required',
            'body' => 'required',
        ]);

        $data = array();
        $data['title'] = $request->title;
        $data['slug'] = str_slug($request->title);
        $data['user_id'] = Auth::id();
        $data['meta_title'] = $request->meta_title;
        $data['meta_description'] = $request->meta_description;
        $image = $request->file('image');
        $data['body'] = $request->body;
        $data['created_at'] = \Carbon\Carbon::now();

        $slug = str_slug($request->title);
        
        if($image) {
            $image_name = $slug . "-" . date('dmy_H_s_i');
            $ext = strtolower($image->getClientOriginalExtension());
            $image_full_name = $image_name . '.' . $ext;

            $upload_path = "public/assets/frontend/uploads/posts/";
            $image_url = $upload_path . $image_full_name;
            $success = $image->move($upload_path, $image_full_name);

            $data['image'] = $image_url;
            $post = DB::table('posts')->insert($data);
            

            $post->categories()->attach($request->categories);
            return redirect(route('admin.posts.index'))->with('successMsg', 'Post has been saved successfully!');
        }
}

laravel报错页面有这行有问题:

$post->categories()->attach($request->categories);

我的数据库中有一个单独的表来连接帖子 ID 和类别 ID,它被称为 category_post 除了 category_post 表中的新记录外,帖子内容被插入到数据库中

那么如何更改该代码以使其正常工作? 谢谢

【问题讨论】:

  • 为什么所有东西都包裹在if ($image) {...}?。这意味着$post 将不会被保存,并且在某些情况下服务器不会响应
  • dd($request->categories) 的输出是什么?

标签: php laravel


【解决方案1】:
DB::table('posts')->insert($data);

根据查询的成功/失败执行返回true|false。如果你想这样写

$post->categories()->attach($request->categories);

然后你需要模式 Post 并像这样创建实例:

$post = new Post;
$post->title = $request->title;
// ...
$post->save();

然后您将拥有Post 类的实例

【讨论】:

  • 谢谢。有没有办法只改变这个 $post->categories()->attach($request->categories);而不是其余的代码?
  • 不,没有。这不会创建类 Post 的新实例
  • 还要注意我的方法不需要$data数组。
  • @PapT 如果您只想更改该部分,您可以将->insert 替换为insertGetId,然后执行$post = Post::find($post); 进行第二次查询以再次获取模型,尽管这非常低效
猜你喜欢
  • 2018-09-06
  • 2020-07-16
  • 1970-01-01
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多