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

rqmkfv5c  于 2022-11-26  发布在  其他
关注(0)|答案(2)|浏览(204)

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

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模型。

w1e3prcc

w1e3prcc1#

变更

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

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

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

mf98qq94

mf98qq942#

在函数定义时这样写

public function destroy($id, Model $model){
    $data = $model::find($id);
    if($data){
        $data->delete();
        return response()->json([
                'status' => 'success',
                'message' => 'Deleted successfully'
            ]);
    }else{
        return response()->json([
                'status' => 'failed',
                'message' => 'Data not found'
            ]);
    }
}

在函数调用时这样写

$this->destroy(5, Video::class);
  • 如果函数在同一个类中定义,则使用$this *

相关问题