【发布时间】:2022-01-27 00:07:25
【问题描述】:
以下代码显示错误TypeError: Argument 1 passed to App\Http\Controllers\StudentLearningController::update() must be an instance of Illuminate\Http\Request, array given
use Illuminate\Http\Request;
class StudentLearningController extends Controller{
public function abc(){
$myCourseData['points'] = "1";
$myCourseData['totalPoints'] = "2";
$this->update($myCourseData,$myCourseId);
}
}
我想传递 2 个参数:points 和 totalPoints 从函数 abc() 到函数 update() 并在 update() 中以 $request->points; 访问 points。我该怎么做?只有points 和totalPoints 是从上述函数传递过来的,update() 函数输入中的其他参数是从其他函数中更新的。
use Illuminate\Http\Request;
trait MyCourseTrait{
function update($request,$id){
$validator = Validator::make(
$request->all(),
[
'course_id' => 'nullable|integer',
'exam_numbers' => 'nullable|integer',
'points' => 'nullable|integer',
'subscription' => 'nullable|boolean',
'totalPoints'=>'nullable|integer'
]
);
$points = $request->points;
}
}
我知道,上面给出的错误是因为我将array 传递给update() 函数的输入。但我不能简单地这样做
$points="1";
$totlaPoints="2";
$this->update($points,$totlaPoints,$myCourseId);
因为 MyCourseTrait 中的 update() 函数不能有超过 2 个参数:$request 和 $id,因为这个函数在我的项目中的其他一些情况下使用,其中只提供了 2 个参数。这是我面临的实际问题。
【问题讨论】:
-
您的代码和错误信息不太吻合。错误提及方法
abc()- 您的代码中没有 any 参数。您的update()方法位于不同的控制器中。设置$points = $request->points;并且不返回任何内容是没有实际用处的。 -
@Jerson 在第一个参数中意味着什么?
-
您应该在请求中附加额外的键值对。 See push()
-
@InsaneSkull 我已经浏览了这个链接。在我的情况下我应该如何实现它?你能给我举个例子吗?请..
-
如果你想在
StudentLearningController中使用自定义函数update类似地在myCourseController控制器中尝试复制它们(仅用于测试)或使用特征。现在在您的代码中使用来自默认类Controller的标准函数update
标签: php arrays laravel validation laravel-8