Home > front end >  Making a custom laravel directive to detect if view is served on mobile or desktop
Making a custom laravel directive to detect if view is served on mobile or desktop

Time:10-13

I have created this directive in my AppServiceProvider and this is the code

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Pagination\Paginator;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\View;

use Illuminate\Support\Facades\DB;
use Blade;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
    Blade::directive('detect', function () {
     if(!empty($_SERVER['HTTP_USER_AGENT'])){
       $user_ag = $_SERVER['HTTP_USER_AGENT'];
       if(preg_match('/(Mobile|Android|Tablet|GoBrowser|[0-9]x[0-9]*|uZardWeb\/|Mini|Doris\/|Skyfire\/|iPhone|Fennec\/|Maemo|Iris\/|CLDC\-|Mobi\/)/uis',$user_ag)){
          return true;
       };
    };
    return false;
         });
    }
}

I now want to use it inside my blade file like this

 <div >
    <label for="exampleInputEmail1" >Category</label>
    <input type="email"  id="exampleInputEmail1" aria-describedby="emailHelp">
  </div>

If the view is being served on mobile i want to display the class col-6 but display col-3 if its being served on desktop.

So far i get the error undefined constant detect.

How can i fix this?

CodePudding user response:

I fixed it this way. In my AppServiceProvider.php

   Blade::if('detect', function ($value) {
      if(!empty($_SERVER['HTTP_USER_AGENT'])){
   $user_ag = $_SERVER['HTTP_USER_AGENT'];
   if(preg_match('/(Mobile|Android|Tablet|GoBrowser|[0-9]x[0-9]*|uZardWeb\/|Mini|Doris\/|Skyfire\/|iPhone|Fennec\/|Maemo|Iris\/|CLDC\-|Mobi\/)/uis',$user_ag)){
      return 'mobile';
   };
    }else{
    return 'desktop';
    }
});

and i am using it this way

<div  

@detect("mobile")

@else
 
@enddetect

    >
    <label for="exampleInputEmail1" >Category</label>
    <input type="email"  id="exampleInputEmail1" aria-describedby="emailHelp">
  </div>

CodePudding user response:

You don't need to overcomplicate the process bootstrap has media statements already handled :) look at this link to help all you need to do is add col-sm-3 for mobile or col-md-6 when it gets to any higher than a tablet Boostrap docs to column responsiveness

  • Related