我想使用另一個(gè)控制器保存信息以將其存儲(chǔ)在數(shù)據(jù)庫(kù)中。在我的情況下,有兩個(gè)控制器:PostingsController評(píng)論控制器我可以使用 CommentsController 為評(píng)論創(chuàng)建創(chuàng)建函數(shù),但我無(wú)法從 CommentsController 將 post_id 保存在數(shù)據(jù)庫(kù)中。我想使用 PostingsController 保存 post_id,因?yàn)樗哂校?/if user did not fill the form properly //error messages will popup $this->validate($request, [ 'comment' => 'required', ]); //if user filled the form properly //store the form $comment = new Comment(); //for connecting both user and comment $comment->user_id = Auth::id(); //to store comment $comment->post_id = //I want to save post_id from PostingsController //to store comment $comment->comment = $request->input('comment'); //save all user input $comment->save(); dd($comment);我設(shè)置了 $comment = Posting::id();,但它不起作用。錯(cuò)誤是:BadMethodCallExceptionCall to undefined method App\Models\Posting::id()
2 回答

慕桂英4014372
TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超13個(gè)贊
遵循關(guān)注點(diǎn)分離的原則,您可以將邏輯移動(dòng)到另一個(gè)模塊中,例如服務(wù)。
我建議添加一個(gè)新文件夾app/services
并為每個(gè)需要實(shí)現(xiàn)的邏輯添加一個(gè)服務(wù)類,例如。app/services/AddCommentToPostService.php
.
這也將使系統(tǒng)的測(cè)試更容易。

阿波羅的戰(zhàn)車
TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用 app 方法在 laravel app('App\Http\Controllers\ControllerName')->functionName() 中調(diào)用另一個(gè)控制器的控制器方法;
- 2 回答
- 0 關(guān)注
- 160 瀏覽
添加回答
舉報(bào)
0/150
提交
取消