嗨,我在laravel中使用一个存储库模式来创建任务,它们都有一个估计的时间,项目有几个小时的容量。因此,我需要在创建任务时将其传递回去,以便他们可以看到还剩下多少小时。
我到目前为止有这个:
TaskRepository.php
public function createTask(array $attributes)
{
if ($this->validator->createATask($attributes)) {
$newAttributes = [
'project_id' => $attributes['project_id'],
'estimated_time' => $attributes['estimated_time'],
'task_name' => $attributes['task_name']
];
$task = Task::updateOrCreate([
'task_name' => $attributes['task_name']
],
$newAttributes);
$task->save();
$project = Project::find($attributes["project_id"])->pluck('capacity_hours');
$tasks = Task::find($attributes["project_id"])->lists('estimated_time');
$tasksTotal = array_sum($tasks);
$capcity_left = ($project - $tasksTotal);
return $capcity_left;
}
throw new ValidationException('Could not create Task', $this->validator->getErrors());
}
在我的控制器中,我有这个:
TaskController.php
public function store() {
try {
$this->task_repo->createTask(Input::all());
} catch (ValidationException $e) {
if (Request::ajax()) {
return Response::json(['errors' => $e->getErrors()], 422);
} else {
return Redirect::back()->withInput()->withErrors($e->getErrors());
}
}
if (Request::ajax()) {
return Response::json(["message" => "Task added",'capcity_left'=> $capcity_left]);
} else {
return Redirect::back()->with('success', true)->with(['message', 'Task added', 'capcity_left'=>$capcity_left ]);
}
}
和我有一个部分的错误:
@if(Session::get('success'))
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
aria-hidden="true">×</span></button>
<strong>{{ Session::get('message', '') }} Capacity Left:{{ Session::get('capcity_left', '') }}</strong>
</div>
@endif
但是我得到这个错误:
Undefined variable: capcity_left
有什么想法我可以把这个传递回控制器吗?我以为我说的是return $capcity_left;
我需要在控制器中捕获这个吗?如果有,我该怎么做呢?
从控制器调用createTask
方法时忘记分配它的返回值。所以你需要这样做:
public function store() {
try {
// assign the return value here
$capcity_left = $this->task_repo->createTask(Input::all());
} catch (ValidationException $e) {
// ...
}