gpt4 book ai didi

php - Laravel将可变成功消息从存储库传递回 Controller

转载 作者:行者123 更新时间:2023-12-03 08:54:26 25 4
gpt4 key购买 nike

嗨,我在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());

}

在我的 Controller 中,我有:

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">&times;</span></button>
<strong>{{ Session::get('message', '') }} Capacity Left:{{ Session::get('capcity_left', '') }}</strong>
</div>
@endif

但是我得到这个错误:
Undefined variable: capcity_left
有什么想法可以将其传递回 Controller 吗?我以为是我说的 return $capcity_left;我需要在 Controller 中捕获吗?如果可以,我该怎么做?

最佳答案

从 Controller 调用时,您忘记分配createTask方法的返回值。因此,您需要这样做:

public function store() {

try {
// assign the return value here
$capcity_left = $this->task_repo->createTask(Input::all());
} catch (ValidationException $e) {

// ...
}

关于php - Laravel将可变成功消息从存储库传递回 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31641215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com