【问题标题】:Laravel eloquent Update FunctionLaravel 雄辩的更新功能
【发布时间】:2020-02-14 05:39:50
【问题描述】:

在模块化开发中使用 Laravel eloquent。保存效果很好,但更新功能没有像我预期的那样工作。请检查我的编码方法和错误。

use Modules\Projects\Entities\Project;
public function update(Request $request, $id)
    {
        $project = Modules\Projects\Entities\Project::find($id);
        $project->project_name = request('project_name');
        $project->save();
}

错误抛出如下:

{
    "message": "Class 'Modules\\Projects\\Http\\Controllers\\Modules\\Projects\\Entities\\Project' not found",
    "exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
    "file": "D:\\XMAPP\\htdocs\\minidmsapi\\Modules\\Projects\\Http\\Controllers\\ProjectsController.php",
    "line": 69,
    "trace": [

如何在模块化开发中使用“$flight = App\Flight::find(1);”? Laravel Official Doc

【问题讨论】:

  • 写在上面:使用 App\Modules\Projects\Entities\Project;
  • 然后改为:$project = Project::find($id);
  • @YasinPatel 谢谢。工作正常。如何获得成功响应?

标签: laravel api eloquent insert-update


【解决方案1】:

你已经导入了Modules\Projects\Entities\Project;。现在你可以直接使用Project了。

use Modules\Projects\Entities\Project;
public function update(Request $request, $id)
{
    $project = Project::find($id);
    $project->project_name = request('project_name');
    $project->save();
}

希望这会有所帮助...

【讨论】:

  • 好的。如何获得成功响应? (我的意思是为检查保存的 ID)@jithesh
  • $project = Project::where('id', $id)->update(['project_name' => request('project_name')]);。然后使用$project->id
【解决方案2】:

尝试在Modules\Projects\Entities\Project::find($id); 之前添加\

点赞\Modules\Projects\Entities\Project::find($id);

或者你可以直接使用Project::find($id);,因为你已经使用了命名空间。

【讨论】:

  • @Vibhaa 好的。如何获得成功响应? (我的意思是为检查保存的 ID)
  • 检查$project->id是否设置
【解决方案3】:

你不必在 Project 模型上使用完整的命名空间,因为你已经在顶部导入了它:

use Modules\Projects\Entities\Project;

只需使用:

$project = Project::find($id);

编辑: 要返回一些响应消息,您可以在下面的函数末尾添加类似这样的内容:

return redirect()->back()->with('success', 'Your message');

为了在刀片中显示您的消息,添加如下内容:

@if (session()->has('success'))
    <div class="alert alert-success">
        <p>{{session('success')}}</p>
    </div>
@endif

【讨论】:

  • 好的。如何获得成功响应? (我的意思是为检查保存的 ID)
  • 我不确定你在问什么。您想要一条显示“已更新项目 id 10(例如)?”的消息
  • @zlatna 完全正确
猜你喜欢
  • 2020-05-30
  • 2017-04-28
  • 2013-09-09
  • 1970-01-01
  • 2017-03-05
  • 2017-08-04
  • 1970-01-01
  • 2018-08-14
  • 2014-08-03
相关资源
最近更新 更多