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

5 MVC Frameworks For PHP Developers in 2016

PHP is one of the most popular open source server side scripting language in the world. The reason behind its popularity is, it is very easy to learn and understand. PHP is more flexible when it comes to writing code because of its features like, weakly typed variables, OOP is not a mandatory.

However, there is a bad side of all this flexibility, it is very easy to write bad code. And the solution to this problem is FRAMEWORK.

There are many benefits of using a framework;

  1. Organization of code is very easy as most the frameworks follow MVC pattern
  2. Most of the frameworks have active community support.
  3. Faster development
  4. Form validation
  5. Pretty URLS

In this post, we are going to go over 5 most popular frameworks in PHP community.

Laravel

Created by Taylor Otwell, Laravel is one the most popular framework. It is one of the most forked project framework on github with very active community support. Laravel’s features include RESTful routing, Blade templating engine, Eloquent ORM, Socialite, Middlewares etc.

laravel

laravel

CodeIgniter

Codeigniter was released in 2006, it is a lightweight PHP framework that comes with unparalled flexibilty and extraordinary documentation. This is the best framework for beginners as it is very easy to understand and learn.

codeignitor

Symfony

Symfony is known as one of the best option for large scale enterprise applications. Licensed under MIT license, it was created by Sensiolabs in 2005. Symfony components are used by many popular open source projects including Drupal, PHPbb and Laravel.

symfony

symfony

CakePHP

CakePHP was initially in 2005 and is one of the most popular framework till date. some of the features of CakePHP are code generation and scaffolding, CSRF protection, form validations, built-in ORM, Helpers, Behaviours, and Plug-ins etc.

cakephp

cakephp

Yii

Yii is a open source PHP framework that follows the MVC pattern. It comes bundled with tons of features that include, a powerful caching system, form validations, integrated with jQuery, and AJAX-enabled features etc.

yii

How to Remove a Package From Laravel Using Composer

We have already discussed how we can install packages and dependencies using Composer dependency manager. In this tutorial, we are going to see how we can remove existing packages from Laravel.

To remove a package navigate to your project folder and use the following command.

composer remove vendor/package

Example:

let’s say, I want to remove the HTML and Form builder package from my Laravel app. Then I need to run the following command.

composer remove laravelcollective/html

Where laravelcollective is the vendor name and html is the name of the package. Also, you need to remove references to that package from providers and aliases arrays from within the app.php.

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.