[英]Laravel: “override” request object?
I have a function where I save a group. 我有一个保存群组的功能。 I want to "access" it from the page (when the user makes a new group with a form) and from a controller, too (when a process makes a new group, for example when I create a new tenant)
我想从页面(当用户使用表单创建新组时)和控制器(例如当流程创建新组时,例如当我创建新租户时)从页面“访问”它
My code is so far: 到目前为止,我的代码是:
.
.
.
$this->saveGroup($tenantId, 'Default group');
.
.
.
public function saveGroup(Request $request, $tenantId = 0, $nameFromFunction = ''){
if(!empty($request)){
$name = $request -> name;
} elseif($nameFromFunction != ''){
$name = $nameFromFunction;
} else {
$name = '';
}
if($tenantId > 0 && $name != ''){
$group = new ConversationGroup;
$group -> group_name = $name;
$group -> tenant_id = $tenantId;
$group->save();
}
if($nameFromFunction != ''){
return $group -> id; //if a function calls it
} else {
return redirect("/{$tenantId}/groups"); //if the new group was made from the page
}
}
If I test it with the page's group creation form it works fine, but when I run it from the controller I got the following error: 如果我使用页面的组创建表单对其进行测试,则可以正常工作,但是当我从控制器运行它时,出现以下错误:
GroupController::saveGroup() must be an instance of Illuminate\\Http\\Request, integer given
GroupController :: saveGroup()必须是Illuminate \\ Http \\ Request的实例,给定的整数
What I must change if I want to earn this logic? 如果我想获得这种逻辑,我必须改变什么?
you could use global request() helper and completely avoid passing Request
object to your function, like: 您可以使用全局request()帮助器,完全避免将
Request
对象传递给函数,例如:
public function saveGroup($tenantId = 0, $nameFromFunction = ''){
//get input named 'name' or default to $nameFromFunction
$name = request('name', $nameFromFunction);
...
The reason this is happening, is because in your function definition, first parameter is not $tenantId
, but the object of class request. 发生这种情况的原因是,在您的函数定义中,第一个参数不是
$tenantId
,而是类请求的对象。
So you have to pass an object of request class as a first parameter to get this working. 因此,您必须将请求类的对象作为第一个参数进行传递才能使其正常工作。
You should try this way, 你应该这样尝试
public function otherFunction()
{
$this->saveGroup(new Request(['name' => 'Default Group']), $tenantID);
OR
$this->saveGroup(new Request(), $tenantID, "Default Group");
}
public function saveGroup(Request $request, $id = 0, $nameFromFunction = '')
{
echo 'here-your-code';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.