嗨我在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;
我需要在控制器中捕获这个吗?如果是这样我怎么能这样做?
答案 0 :(得分:0)
从控制器调用时,您忘记分配createTask
方法的返回值。所以你需要这样做:
public function store() {
try {
// assign the return value here
$capcity_left = $this->task_repo->createTask(Input::all());
} catch (ValidationException $e) {
// ...
}