Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - How to use a vendor class?

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.

like image 441
jstudios Avatar asked Oct 17 '14 19:10

jstudios


2 Answers

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.

like image 174
Matthew Brown Avatar answered Nov 15 '22 07:11

Matthew Brown


I was also struggling with the mobile detection in Laravel, but I found the solution! This is from the beginning (incl. installation):

  • in the terminal in your Laravel project folder:

    $ composer require mobiledetect/mobiledetectlib
    
  • in a Middleware file for mobile detection:

    use Mobile_Detect;
    
    ...
    
    $detect = new Mobile_Detect;
    
    if ($detect->isMobile()) var_dump('is mobile');
    else var_dump('is not mobile');
    

And you are ready to go ;)

like image 31
tsveti_iko Avatar answered Nov 15 '22 08:11

tsveti_iko