我写了一个控制器,它可以从数据库中删除一条记录,这是非常简单的。代码如下所示。
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模型。
2条答案
按热度按时间w1e3prcc1#
变更
至
模型
Model
并不作为示例存在,使用字符串作为模型是可行的,只是不要暗示它。mf98qq942#
在函数定义时这样写
在函数调用时这样写
$this
*