View Composers in laravel

When you start working on laravel, you will come into the situation where you require same data in multiple views. ie, sidebars or side widget. so it’s not a good idea to fetch same data again and again for every views. so for this we can use view composer which will help you to get same data multiple views without calling multiple times.

For this we are going to consider AppServiceProvider.php which lies inside Providers folder. There are two functions inside AppServiceProvider.php, one is boot(), another is register(). But here we are going to make use of boot() function. In boot function you can perform any action assuming that framework is fully loaded. Now make use of view helper function as shown below:

<?php
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {

        view()->composer('layouts.sidemenu',function($view){
            $notificationinfo=new NotificationAlertController();
            $view->with('notificationCount',$notificationinfo->showNotificationCount());
        });
    }

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

Here we can hook into when any view is loaded. It’s just like a callback. Now let me go to my view which makes use of sidemenu all the time. This sidemenu is called from all other views. In my sidebar I have notification count, so I have decided which ever views call sidebar, it should show notification count.

Now let us explain in brief about the code that we have written inside the boot(). When a layout.sidemenu is loaded in any views, we call a callback function where we can bind anything to that view. Within a callback function, i have created an object for NotificationAlertController.

Then I have called a function with that controller named as showNotificationCount(), from this function we are getting a value of notificationcount, which in turn we are binding that returned value to the view.

Now let enclose function showNotificationCount() of NotificationAlertController too.

<?php
class NotificationAlertController extends Controller
{
 public  function showNotificationCount(){

        $notificationCount=DB::table('current_device_profile_infos')
            ->select('current_device_profile_infos.vin_number', 'battery_level', 'fuel_level', 'mileage', 'id')
            ->where('battery_level', '<', 12.5)
            ->orWhere('fuel_level', '<', 20)
            ->orWhere('mileage', '>', 11000)->count();

        return $notificationCount;
    }

}

Now which ever view you click into, but the notification count is displayed everywhere. This is a short and easy explanation on view composer.

If you have any query, feel free to contact me.

Laravel Pagination links not including other GET parameters

When there are some GET parameters in the URL,
eg: http://yoursiteurl.com/search-vehicle-profile?startdate=07%2F28%2F2017&enddate=08%2F01%2F2017&vin_number=2HGFC2F89GH033029, the pagination links produced only contain the page parameter and nothing else as http://yoursiteurl.com/search-vehicle-profile?page=2

This happens when you use link in your blade as {{ $vehicleHistoryDetail->link() }}

so rather than just using that, you need to you appends function as shown below

{{ $vehicleHistoryDetail->appends(request()->input())->links() }}

Raw Query in Laravel

We can write raw query in laravel as shown below. Here we have made use of where, where in, with ‘and’ and ‘or’ condition. The most important thing you need to consider while writing raw query is DB::select( DB::raw())


  $vehicleHistoryDetail =
            DB::select( DB::raw("SELECT mdi_ext_batt_voltage,mdi_dashboard_fuel_level,mdi_obd_mileage FROM vehicle_info_devices WHERE profile_id IN (1,2)and(
        mdi_dashboard_fuel_level <> 0 or mdi_ext_batt_voltage <> 0 or mdi_obd_mileage <> 0) ") );

Fun with Array

I have a locationlist class which has geographical latitude and longitude as shown below


<?php 
namespace App\LocationProviders; 
class LocationList 
{ 
public function getLocations() 
{ 
       $locationCoords = []; $locationCoords[0] = [ ["lat" => 43.75812569798546, "lng" => -79.79318417608738],
            ["lat" => 43.758138774543475, "lng" => -79.7931607067585],
            ["lat" => 43.75810390371577, "lng" => -79.7931244969368],
            ["lat" => 43.75809034283284, "lng" => -79.79314729571342]
        ];

        $locationCoords[1] = [
            ["lat" => 43.7581397431773, "lng" => -79.79315668344498],
            ["lat" => 43.758152819732246, "lng" => -79.7931332141161],
            ["lat" => 43.75811843322978, "lng" => -79.7930970042944],
            ["lat" => 43.758105356667315, "lng" => -79.79311980307102]
        ];
        $locationCoords[2] = [
            ["lat" => 43.7581547569994, "lng" => -79.79312919080257],
            ["lat" => 43.7581673492344, "lng" => -79.7931070625782],
            ["lat" => 43.758132962740284, "lng" => -79.79307018220425],
            ["lat" => 43.75812037049805, "lng" => -79.79309231042862]
        ];

    return $locationCoords;
     }

}

Now what I intend to do is, I want to have array of latitude and array of longitude for the array $locationCoords[0],$locationCoords[1],$locationCoords[2] and so on.For this i have written below code


public function vehicle_map_with_info()
    {

      $locationListInfo = new LocationList();

        $locationinfo = $locationListInfo->getLocations();

        $newCoordinateArr = [];
        foreach ($locationinfo as $key => $value) {
            $latitudeArr = [];
            $longitudeArr = [];
            foreach ($value as $keyanother => $anothervalue) {

                $latitudeArr[] = $anothervalue['lat'];
                $longitudeArr[] = $anothervalue['lng'];
            }
            $newCoordinateArr[$key]['lat'] = $latitudeArr;
            $newCoordinateArr[$key]['lng'] = $longitudeArr;


        }

        echo "<pre>";
        //print_r($latitudeArr);
        return $newCoordinateArr;

}

Here it is, now you can get array in the form as shown below:


[
{
"lat": [43.75812569798546,43.758138774543475,43.75810390371577,43.75809034283284],
"lng": [-79.79318417608738,-79.7931607067585,-79.7931244969368,-79.79314729571342]
},
{
"lat": [43.7581397431773,43.758152819732246,43.75811843322978,43.758105356667315],
"lng": [-79.79315668344498,-79.7931332141161,-79.7930970042944,-79.79311980307102]
}
]

Fun with Array -2

Now i have another requirement too, that is i want array of latitude and longitude in the form of

$finalcoordinates=array("lat1 lng1","lat2 lng2","lat3 lng3"); ie

$finalcoordinates = array("43.7592439755264 -79.79324888437986","43.759231383517985 -79.79323044419289","43.759203535797674 -79.79327369481325","43.759215643503765 -79.7932904586196","43.7592439755264 -79.79324888437986");

In order to get this output i have written a code as shown below:


public function vehicle_map_with_info($vin_id)
    {
        $locationObj = new FindLocation();
        $locationinfo = $locationObj->showLocations();

        foreach ($locationinfo as $key => $value) {
            $newCoordinateArr = [];
            foreach ($value as $seckey => $finalvalue) {
                $newCoordinateArr[$seckey] = $finalvalue['lat'] . " " . $finalvalue['lng'];

            }
          
          
        }

        return $newCoordinateArr;
}

Now you get your output as


[
"43.758909802097 -79.794197380543",
"43.758935954868 -79.794150441885",
"43.758917551068 -79.794130325317",
"43.758891398289 -79.794177263975",
"43.758909802097 -79.794197380543"
]

Hope it gives solution to your problem.

Enable user register even after login laravel 5

In order to enable user register even after logging in laravel, you can do following simple step:

1. Go to your RegisterController.php which is inside controllers followed by Auth.

There you get code as shown below

   public function __construct()
    {
        $this->middleware('guest');
       
    }

You can remove the $this->middleware() line entirely to prevent the middleware being applied to all your login and register routes.

This will enable you to register user even after login.

Laravel 5 Class ‘form’ not found

When i was trying to run my laravel application with form tags like:

{!! Form::label('featured_image','Select Featured Image',array('id'=>'','class'=>'')) !!}
{!! Form::file('image',array('class'=>'imageUpload','id'=>'uploadFile')) !!}

I got an error with Laravel 5 Class ‘form’ not found
With some research, i found a solution for it. Here are some steps to solve it.

1. Go to your composer.json file
2. Include “laravelcollective/html”: “^5.2.0” within require
3. then update your composer using a command in your terminal :\> composer update

Once the composer is updated

4. Now go to your app.php file within config folder
5. In providers add following code

  Collective\Html\HtmlServiceProvider::class,

6. then go to alias section and add below code

   'Form' => Collective\Html\FormFacade::class,
   'Html' => Collective\Html\HtmlFacade::class,

Now run your application and you are free of error.