1

I have a very basic function to delete stuff on a simple website on Laravel 4.x that works like this:

public function delete()
{
    ...
    $Model = Input::get('Model');       
    $Action = $Model::find($Id);
   ...
}

Now on Laravel 5, I'm trying to do the same but so far I can't because the namespaces. Since the $Model is dynamic I don't want to make use for everything.

And something like this:

use App\C\Models as Model;

public function delete()
{
...
$Action = Model\$Model::find($Id);
...
}

Simple do not works. What'd be the right approach to get this to work?

2 Answers 2

11

Simply store the namespaced classname as a string first:

$Model = Input::get('Model');
$NamespacedModel = '\\Model\\' . $Model;
$Action = $NamespacedModel::find($Id);
Sign up to request clarification or add additional context in comments.

3 Comments

i have been try like code in your comment, but i have error syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)
@VinraGunantaPandia Maybe your PHP version is too old? I believe this was added in PHP 5.3
not because that, i must named variable with $class, $class = '\\Model\\' . $Model; $Action = $class::find($Id); and now its work
3

In the same case, My code is like this...

public function FunctionName(Request $request)
{
    $modelName = $request->model;

    $model = '\\App\\Models\\'.$modelName;

    $q = $model::find($request->id);

    $q->someColumn = 'someValue';

    $q->save();

    return back();
}

Note: I am using Laravel 8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.