Laravel Facebook Login guide how-to

This is a detailed guide how to implement Facebook login on your Laravel project.

If you are just starting, create new laravel project,

laravel new blog

Next you need to set up database, create .env file ( with credentials to your database ) and start by running following commands:

php artisan migrate
composer require laravel/socialite
composer require doctrine/dbal

Open config/app.php and add these 2 lines to appropriate sections:

'providers' => [
	Laravel\Socialite\SocialiteServiceProvider::class
],

'aliases' => [
	'Socialite' => Laravel\Socialite\Facades\Socialite::class
],

You can add these as the last items. Next open config/services.php and add in credentials from your facebook application. If you don’t have one yet, create it here https://developers.facebook.com/

'facebook' => [
        'client_id' => env('FACEBOOK_CLIENT_ID'),
        'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
        'redirect' => env('FACEBOOK_CALLBACK_URL')
]
And add these to your .env file. Example given:
FACEBOOK_CLIENT_ID=38268********
FACEBOOK_CLIENT_SECRET=6f8de45093*********
FACEBOOK_CALLBACK_URL=https://laravel.test/auth/facebook/callback

Next we need to make minor changes in database, so run:

php artisan make:migration facebook

and edit the newly created file in database/migrations/***_facebook.php Change it like this

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class Facebook extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table("users", function (Blueprint $table) {
            $table->string('facebook_id');
            $table->string('password', 255)->nullable(true)->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table("users", function (Blueprint $table) {
            $table->dropColumn('facebook_id');
        });
    }
}

– thrugh this we have added new column to users table called ‘facebook_id’ and more importantly, we have changed existing ‘password’ column to be nullable. Without this, it wouldn’t work.

You can execute these changes now

php artisan:migrate

Almost there!
Edit app/User.php add facebook_id into list of editable fields, e.g.

protected $fillable = [
        'name', 'email', 'password', 'facebook_id'
];
And add a new function
public function addNew($input)
    {
        $check = static::where('facebook_id',$input['facebook_id'])->first();


        if(is_null($check)){
            return static::create($input);
        }


        return $check;
}
Which we will use in a moment. Next step update routes/web.php by adding following few lines
Route::get('facebook', function () {
    return view('facebook');
});
Route::get('auth/facebook', 'Auth\FacebookController@redirectToFacebook');
Route::get('auth/facebook/callback', 'Auth\FacebookController@handleFacebookCallback');
And last step ahead – create facebook controller.
php artisan make:controller Auth/FacebookController
change it to following
<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Socialite;
use Exception;
use Auth;

class FacebookController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToFacebook()
    {
        return Socialite::driver('facebook')->redirect();
    }
    
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleFacebookCallback()
    {
        try {
            $user = Socialite::driver('facebook')->user();
            $create['name'] = $user->getName();
            $create['email'] = $user->getEmail();
            $create['facebook_id'] = $user->getId();

            $userModel = new User;
            $createdUser = $userModel->addNew($create);
            Auth::loginUsingId($createdUser->id);

            return redirect('/u/');

        } catch (Exception $e) {
            return redirect('auth/facebook');
        }
    }
}

And that’s it! It’s done – you are a guru! Now just open any template where you want a login button and link to /auth/facebook page on your site. Upon successful authorization you will be redirected back to landing page, but you will be authorized now.

You can even update web.php to have your own “logged in only zone”, for example:


Route::get('/', 'PageController@welcome');
Route::get('login', 'PageController@login')->name('login');
Route::get('auth/facebook', 'Auth\FacebookController@redirectToFacebook');
Route::get('auth/facebook/callback', 'Auth\FacebookController@handleFacebookCallback');

Route::group(['middleware' => 'auth', 'prefix' => 'u'], function () {
    Route::get('/', 'LoggedInController@home');

});
And everything under /u/* url is for authorized users only.

PrestaShop – check product category in smarty .tpl

If you need to display some block based on product’s category and you want to check for that category right in the smarty template ( e.g. product.tpl ) you can do so using this code – which as an example uses category 27 as base reference. You can easily find your category ID in admin.

{assign var='cats' value=Product::getProductCategories($product.id)}
{if in_array(27, $cats)}
.. following will only be displayed if this product is in category of ID 27
{/if}

If you for some reason can’t find your category ID, you can look for it by adding following into product.tpl

{assign var='cats' value=Product::getProductCategories($product.id)}
{$cats|@print_r}
Just reload page and you will see in which categories this product is. Alternatively you could use
{debug}
to access all smarty available variables and look in there.

Laravel – remove vendor from git

In case you have accidentally committed your vendor folder, you can easily remove it by following these steps:

git rm -r --cached vendor
git rm -r --cached composer.lock
git commit -m "untrack vendor directory"
git push

[Laravel 5] Call to undefined method Illuminate\Foundation\Bootstrap\ConfigureLogging::configureHandler()

If you are getting following error:

PHP Notice:  date_default_timezone_set(): Timezone ID '' is invalid in /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php on line 45

[2017-10-16 19:50:38] production.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined method Illuminate\Foundation\Bootstrap\ConfigureLogging::configureHandler() 
                                                                                                 
  [Symfony\Component\Debug\Exception\FatalThrowableError]                                        
  Call to undefined method Illuminate\Foundation\Bootstrap\ConfigureLogging::configureHandler()  
                                                                                                 

Try editing composer.json and set laravel/framework to 5.*, e.g.

        "laravel/framework": "5.*",

Then run composer update again.
Also, make sure config/app.php exists!

Speed up Woocommerce WordPress

Add following few lines into functions.php ( in your theme directory ), at the very bottom.


add_action( 'wp_enqueue_scripts', 'remove_woocommerce_when_not_needed', 99 );

function remove_woocommerce_when_not_needed() {
	remove_action( 'wp_head', array( $GLOBALS['woocommerce'], 'generator' ) );

	if ( function_exists( 'is_woocommerce' ) ) {

		if ( ! is_woocommerce() && ! is_cart() && ! is_checkout() ) {
			// dequeue styles
			wp_dequeue_style( 'woocommerce_frontend_styles' );
			wp_dequeue_style( 'woocommerce_fancybox_styles' );
			wp_dequeue_style( 'woocommerce_chosen_styles' );
			wp_dequeue_style( 'woocommerce-general' );
			wp_dequeue_style( 'woocommerce-layout' );
			wp_dequeue_style( 'woocommerce-smallscreen' );
			wp_dequeue_style( 'sv-wc-payment-gateway-payment-form' );

			// dequeue scripts
			wp_dequeue_script( 'wc_price_slider' );
			wp_dequeue_script( 'wc-single-product' );
			wp_dequeue_script( 'wc-add-to-cart' );
			wp_dequeue_script( 'wc-cart-fragments' );
			wp_dequeue_script( 'wc-checkout' );
			wp_dequeue_script( 'wc-add-to-cart-variation' );
			wp_dequeue_script( 'wc-single-product' );
			wp_dequeue_script( 'wc-cart' );
			wp_dequeue_script( 'wc-chosen' );
			wp_dequeue_script( 'woocommerce' );
			wp_dequeue_script( 'jquery-blockui' );
			wp_dequeue_script( 'jquery-placeholder' );
			wp_dequeue_script( 'fancybox' );
			wp_dequeue_script( 'jqueryui' );
			wp_dequeue_script( 'braintree-data' );
			wp_dequeue_script( 'braintree-js' );
			wp_dequeue_script( 'sv-wc-payment-gateway-payment-form');
		}
	}
}

Scripts checks if the page you are on actually needs woocommerce component ( e.g. product page, checkout page .. ) – if not, it will remove all scripts and styles related to Woocommerce and Braintree.

It’s also possible to disable woocommerce entirely on these pages through dedicated plugin – https://wordpress.org/plugins/plugin-organizer/

Also make sure you update maximum memory limit https://phpsolved.com/wordpress-adjust-maximum-memory-limit/