gpt4 book ai didi

Laravel 将模型类作为函数中的参数传递

转载 作者:行者123 更新时间:2023-12-05 01:17:31 24 4
gpt4 key购买 nike

我编写了一个 Controller ,它可以从数据库中删除一条记录,这非常简单。代码如下所示。

public function destroy(Request $request)
{
try {
MyModel::where('id', json_decode($request->get('data'),true)['id'])->delete();
return response()->json([
'status' => 'success',
'message' => 'Deleted successfully'
]);
} catch (\Exception $e) {
return response()->json(['status' => 'error', 'message' => 'Something went wrong!!', 'exception_message' => $e]);
}
}

现在我想在一个常见的地方使用删除的逻辑,会有很多模型都有销毁功能。所以我写了这个

public function destroy(Request $request)
{
return Crud::destroy(MyModel::class, $request);
}

粗粮类

<?php


namespace App\Helper;


use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class Crud extends Controller
{

public static function destroy(Model $model,Request $request)
{
try {
$output = $model::where('id', $request->get('id'))->delete();
return response()->json([
'status' => 'success',
'message' => 'Deleted successfully',
'output' => $output
]);
} catch (\Exception $e) {
return response()->json(['status' => 'error', 'message' => 'Something went wrong!!', 'exception_message' => $e]);
}
}

}

?>

但是当我调用 destroy 函数时,我得到了错误,因为 Type error: Argument 1 passed to App\Helper\Crud::destroy() must be an instance of Illuminate\Database\Eloquent\Model, string given,

如何在函数中传递 Laravel 模型。

最佳答案

改变

public static function destroy(Model $model,Request $request)
{ ... }

public static function destroy($model,Request $request)
{ ... }

模型 Model 不作为实例存在。使用字符串作为模型是可行的,只是不要暗示它。

关于Laravel 将模型类作为函数中的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49833947/

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