Get Specific Columns Using Eloquent Relationships In Laravel

Here’s a handy Laravel code snippet which allows you to select specific fields using Laravel’s Eloquent relationships. Lets say we have two tables, users and posts. A user has many posts while the post belongs to single user.

Then, in my User model I can write something like,

public function post(){
        return $this->hasmany('post');
}

This will fetch all the columns from post table that belongs to specific post. However, if you want to summon only a specified columns you can do that using the select method.

public function post(){
        return $this->hasmany('post')->select(['title','slug']);
}

Quick Tip : Set friendly names for validation attributes in Laravel

Check If Database Table Has Column in Laravel

Laravel comes with a handy built-in hasColumn method which allows the developers to determine whether a a specific column exists in a particular table or not.

You can use hasColumn method as follows;

if(Schema::hasColumn('users', 'email'))
{
    //do something if email column exists inside users table
}

The above code will check if an email column exists inside the users table.

Quick Tip : How to Override Default Controller Namespace in Laravel

How to Fix MassAssignmentException in Laravel

Mass assignment is a security vulnerability, which occurs when a malicious user passes unexpected HTTP parameters along with the request to the web server in order to gain access he is not supposed to.

Laravel comes with a built-in feature which allows you to protect your application against this security risk. In Laravel, you need to manually specify the list of database columns i.e variables you need to save inside the database using Eloquent’s create method which can be Mass Assigned. To specify the list of variables you need to use $fillable property inside your Model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $fillable = ['first_name','last_name'];
}

For example, we can make first_name and last_name in Laravel Mass assignable by passing it to protected $fillable property in form of an array. You can also specify a list of database columns which cannot be mass assigned using the $guraded property in a similar way.

Whenever you try to save a variables using Eloquent’s create method which are not Mass assignable, Laravel will throw a MassAssignmentException error to your screen.

Read Also: Integrating Facebook Login into Laravel application

Integrating Facebook Login into Laravel application

In this tutorial, we are going to create a Facebook login feature for Laravel 5 using Socialite package.

Note: In order to complete this tutorial, you should have a basic understanding of Laravel Framework.

Step 1: Installation and Configuration:

a) To get started, navigate to your Laravel installation and type the following command to install socialite

composer require laravel/socialite

Recommended: How to Install composer on Windows with XAMPP

b) In the next step, open to config/app.php and add the code given below to providers array.

socialite-facade

socialite-facade

c) Also, add the Socialite’s facade to aliases.

socialite

socialite

Socialite is now registered within your application.

Step 2: Create a Facebook App:

a) Visit Facebook Developer Page and create a new app.

Recommended: http://coffeecupweb.com/how-to-get-an-app-id-and-secret-key-from-facebook/

b) After creating the app, navigate to App > Settings > Add platform.

c) In Select Platform Popup, select Website. 

d) This will create a new Website Section on settings page. Within Website section look for Site URL textbox. In this textbox enter your websites URL.

e) And, copy the App ID and App Secret for your application.

Step 3: Add Facebook App ID and Secret to Your Application:

Navigate to app\services.php and the following details,

'facebook' => [
    'client_id' => 'facebook_app_id',
    'client_secret' => 'facebook_app_secret',
    'redirect' => 'redirect_url',
 ],

redirect is the URL where user will be redirected after authentication.

Step 4: Setup routes and controller methods

We are going to create to routes in our application, one for redirecting user to authentication page and second will be the callback where user will be redirected after authentication.

Define routes for laravel socialite

Define routes for laravel socialite

Note: Add these routes inside web middleware group in routes file.

Next, we need to create redirectToFacebook and handleCallback methods inside Auth\AuthController.php file.

AuthController Socialite

AuthController Socialite

Make sure, you have added socialite class reference at the top of the controller.

use Socialite;

Once you have user instance inside handleCallback, you can grab the details available within the instance and can save it to your database.

That’s it. In case you have any queries, please let me know.

How to Use Soft Delete in Laravel 5

In addition to deleting the records, Laravel’s Eloquent also allows you to perform Soft Delete. In Soft Delete,  a deleted_at column is added to your database table. By default, all records contains NULL value in deleted_at column. When a record has NON-NULL deleted_at value it is considered soft deleted. Soft deleted records are excluded from Eloquent’s query results by Laravel.

In this tutorial, we are going to implement Soft Delete feature.

Step 01 : Add deleted_at Column to Database

Before using soft delete feature you need to add a deleted_at column to database table. Laravel’s Schema builder comes with a built-in method to create this column.

Schema::table('motorcycles', function ($table) {
    $table->softDeletes();
});

Step 02 : Use the Soft Delete Trait in the Model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Motorcycle extends Model
{
    use SoftDeletes;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];
	
	/**
     * The table used by the model.
     *
     * @var string
     */
    protected $table = 'motorcycles';
}

To enable Soft Deletes, use Illuminate\Database\Eloquent\SoftDeletes trait inside your model and add deleted_at to $dates property.

Now, you can soft delete a record using the delete method.

public function destroy($id)
{
	$motorcycle = Motorcycle::find(8);
	$motorcycle->delete();
}

The above code will set the deleted_at value for that specific record to current date and time i.e. non-null value.

Laravel Tip : Rendering View to a String

How to Create a Custom Validation Rule in Laravel

Laravel’s built-in Validation feature comes with a bunch of validation rules like required, email, array etc. But, in some situations you may want to create your own custom rule. For example, in this tutorial we are going to create a validation rule which will check if the email address provided by user belongs to Gmail or not.

To create a custom validation rule follow the steps given below;

Step 1 : Define the rule:

In the first step we are going to define a new rule by extending the Laravel Validator class. We are going to put our new validation rule inside app\Providers\AppServiceProvider.php file that comes bundled with Laravel. You can also use your own custom service provider to put this code.

Validator::extend('gmail', function($attribute, $value)
{
     $domain = explode('@', $value);
     return (isset($domain[1]) && $domain == 'gmail.com') ? true : false;
});

In the above code, gmail is the name of the of our newly created validation rule. The method will return return TRUE if the validation is passed else it will return FALSE. 

Step 2 : Create Custom Validation Message

To set a custom validation message for our rule add the following code to main validation array.

'gmail' =>  'The :attribute must be a valid Gmail Address',

To use the new rule add it to rules array.

$rules = [
        'email' => 'required|gmail',
];

And that’s it. I case you have any queries feel free to comment.

How to Create Model And Migration Using a Single Artisan Command

To generate a model and a migration file you need to run two separate commands.

Quick Tip : How to Create a Service Provider in Laravel 5.1

For model,

php artisan make:model Ticket

And For migration,

php artisan make:migration create_tickets_table --create=tickets

But, while going through Laravel documentation, I have found out that you can do both of these tasks in a single command.

You can use anyone of the following commands to generate both of these files at the same time.

php artisan make:model Ticket --migration

Or,

php artisan make:model Ticket -m

After executing anyone of the above commands we will get a,

Ticket.php (Model):

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Ticket extends Model
{
    //
}

And 2015_11_22_122910_create_tickets_table.php (Migration):

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTicketsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tickets', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('tickets');
    }
}

In case you have any query, feel free to comment.

How to Create a Custom Service Provider in Laravel

In this short tutorial, we are going to create and register a custom service provider in Laravel.

Quick Tip : How to Determine if a View Exists in Laravel

First, open your command prompt, navigate to your project folder and run the following command.

php artisan make:provider DemoServiceProvider

This will generate a new file with name DemoServiceProvider.php located at app\Providers. Your service provider should look something like this:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class DemoServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

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

As you can see, all the service providers extends Laravel’s ServiceProvider class.

To register this provider navigate to config directory located in the root directory of your application and open app.php file. Now, we need to add our provider to the array of providers,

'providers' => [
    .
    .
    .
    App\Providers\DemoServiceProvider::class,
],

And that’s it. We have successfully created and registered a Laravel service provider.