skip to Main Content

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

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;

use IlluminatePaginationPaginator;

use IlluminateSupportFacadesAuth;

use IlluminateSupportFacadesView;

use IlluminateSupportFacadesDB;
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 class="mb-3  
    @if(detect)         
     col-6     
    @else
    col-3       
    @endif
    expand_on_mobile">
    <label for="exampleInputEmail1" class="form-label">Category</label>
    <input type="email" class="form-control" 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?

2

Answers


  1. Chosen as BEST ANSWER

    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")
    class="mb-3 col-6 "
    @else
    class="mb-3 col-3 " 
    @enddetect
    
        >
        <label for="exampleInputEmail1" class="form-label">Category</label>
        <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
      </div>
    

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search