Ad

Route Model Binding And Encryption On Laravel

When trying to bind an encrypted company id to a URL I'm coming across an error. I'm assuming I have every thing I need included and that I can use a custom name like companyEncrypt as it's a custom binding.

Error:

FatalErrorException in RouteServiceProvider.php line 48:
Class 'App\Providers\App\Company' not found

use Log;
use Crypt;
use App\Company;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

Code:

public function boot(Router $router)
{
    parent::boot($router);

    // An a binder for the encrypted company value.
    $router->bind('companyEncypt', function($encryptedValue) {
        try { 
            $decrypted = Crypt::decrypt($encryptedValue);
        } catch (DecryptException $e) {
            Log::info('Dectypt Exception for the company id');
            dd('error');
        }

        return App\Company::where('id', $decrypted)->first();
    });
}

Has anyone come across this before?

Ad

Answer

You need to refer to your Company by either Company or \App\Company.

Replace

return App\Company::where('id', $decrypted)->first();

with

return Company::where('id', $decrypted)->first();

The reason for the error is that when you refer to a class name that is not a fully qualified class name (e.g. \App\Company) or the imported class name (e.g. Company that you're importing it with use App\Company), autoloader looks for the class in the current namespace.

Threfore, if you refer to App\Company in App\Providers namespace, it tries to load App\Providers\App\Company class.

Ad
source: stackoverflow.com
Ad