在我的laravel项目中,我创建了一个控制器,用于删除所有刀片中的项目调用相同的控制器。通过动态id和模型名称。但是找不到类的错误。 例如:Class' User'没找到。
如何添加用户;我的控制器中的代码动态。
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AjaxController extends Controller
{
public function deleteItem(Request $req)
{
use $req['model'];
$id = $req['id'];
$model_name = $req['model'];
$mdoel_name = $model_name::find($id);
$mdoel_name->delete();
sactivity('delete')->performedOn($mdoel_name)->log('');
return "success";
}
}
答案 0 :(得分:8)
这应该有效:
$id = $req['id'];
$model_name = '\\App\\'.$req['model'];
$model = new $model_name;
$model_name = $model->find($id);
$model->delete();
sactivity('delete')->performedOn($model_name)->log('');
return "success";
答案 1 :(得分:1)
将命名空间类名存储为字符串:
$Model = Input::get('Model');
$NamespacedModel = '\\Model\\' . $Model;
$Action = $NamespacedModel::find($Id);