我编写了一个从数据库中删除记录的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);
}
Crud Class
<?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模型。
答案 0 :(得分:1)
更改
public static function destroy(Model $model,Request $request)
{ ... }
到
public static function destroy($model,Request $request)
{ ... }
模型Model
不作为实例存在。使用字符串作为模型可以起作用,但不要暗示它。