Laravel - How to use a vendor class?

jstudios picture jstudios · Oct 17, 2014 · Viewed 25.6k times · Source

I want to use Mobile Detect on m routes.php file. I have added the package as a require in composer.json and it's installed in the vendor file. How can I use it now?

I tried this answer and no luck because the class wasn't found: Laravel 4 using vendor classes

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "laravel/framework": "4.2.*",
        "mobiledetect/mobiledetectlib": "*"
    },
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "stable"
}

EDIT: I tried using this one: https://github.com/jenssegers/Laravel-Agent, but the alias never worked saying the class was not found.

Answer

Matthew Brown picture Matthew Brown · Oct 17, 2014

This package is PSR-0 namespaced. Looking at the git repo, it appears to be Detection\MobileDetect though you will want to make sure this is indeed the correct namespace. Have you tried adding the proper namespace to your routes.php file?

use Detection\MobileDetect as MobileDetect;

or you can reference the proper namespace inline. Here is an example:

$detect = new Detection\MobileDetect\Mobile_Detect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');

If this doesn't work for you, you may be able to get away by adding it to your composer.json classmap:

"autoload": {
    "classmap": ["/vendor/serbanghita/namespaced/"],
}

Of course, fill in the proper path then run a composer dump-auto.