Dynamically use model in laravel

Rafik malek

In my laravel project I create a controller for delete the item from all the blade call the same controller.With passing dynamic id and model name. but showing an error for class not found. ex: Class 'User' not found.

How can I add use User; code in my controller dynamically.

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";
    }
}
Alexey Mezenin

This should work:

    $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";

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Dynamically use of model to send relationship value in a view in laravel

Call laravel model dynamically

How to dynamically set foreign key in a eloquent model laravel and how to use it with withCount

Dynamically add accessor methods in Laravel Model Class

Laravel 5 - Use variables of model in model factories

When to use an eloquent model in laravel

How to use if statement in laravel model

Laravel withCount use function in model

Use Model Function In Laravel Query

When to use ::query in Laravel model?

How to use model values in dynamically model class to Retrofit requests?

Laravel Nova: Dynamically bind fields to JSON attribute on model

Why is the hidden field in the Laravel Model not working when set dynamically?

Use model variable names dynamically in Razor C#

Use ng-Model dynamically based on preset variable

Is there a way to use a field's value in the Model to set a style attribute dynamically?

How to use orderBy() with model's method in Laravel

Use Model Scope in Laravel Validation Rule

PHP Laravel - How to use xSQL FUNC in model?

How to use multiple implements in laravel model

Laravel use model property in relation method

Laravel 5.2 model static functions use

Laravel - Use a column from a model relation

Modify Laravel model response to use different ID

how to use model in laravel to get value?

How to use where with Laravel Eloquent Model

Laravel Select Name and id of Model and use in SelectBox

Use a model instance in different controller - Laravel 5

How to use authentication on custom model in Laravel