duangou1868 2017-09-28 11:48
浏览 81
已采纳

Laravel attach为belongsToMany关系返回undefined方法

I would like to create a question which has many surveys. In the questions Model:

public function surveys()
{
    return $this->belongsToMany(Survey::class, 'survey__surveyquestions');
}

And in the controller when saving a new question:

private $questions;

public function __construct(QuestionsRepository $questions)
{
    parent::__construct();

    $this->questions = $questions;
}

public function store(Request $request)
{
    $this->questions->create($request->all());

    $this->questions->surveys()->attach($request->surveys);

    return redirect()->route('admin.survey.questions.index')
        ->withSuccess(trans('core::core.messages.resource created', ['name' => trans('survey::questions.title.questions')]));
}

But I get the following error when it gets to the attach line:

(1/1) FatalErrorException Call to undefined method Modules\Survey\Repositories\Eloquent\EloquentQuestionsRepository::surveys()

I notice the error mentions EloquentQuestionsRepository but I have added no methods in there so it's just an empty class:

class EloquentQuestionsRepository extends EloquentBaseRepository implements QuestionsRepository
{
}

QuestionRepository:

interface QuestionsRepository extends BaseRepository
{
}
  • 写回答

1条回答 默认 最新

  • dougan5772 2017-09-28 13:10
    关注

    As explained in the response to the main post - the constructor resolves the QuestionsRepository to instance of EloquentQuestionsRepository, which by the look of it is not what the store method needs.

    What I would probably do is to make call to create method directly on the model and remove constructor all together - that is unless you need the instance of QuestionsRepository anywhere else in your controller:

    public function store(Request $request)
    {
        $question = Question::create($request->all());
    
        $question->surveys()->attach($request->surveys);
    
        ...
    
    }
    

    Also - I'm not sure passing $request->all() is the best thing to do - I'd probably use $request->only(...) or $request->all(...) specifying which items you want to get from the request rather than passing everything from the request to the create method.

    On the other note - you could also use Form Request, which would validate data for your before passing it to the store method.

    https://laravel.com/docs/5.5/validation#form-request-validation

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?