What’s New in Laravel 5.5

Laravel 5.5 is scheduled to be released in August of 2017 and is slated for the next major and the LTS release. in every new release of the frameworks, there’s always some cool new features to investigate.so let’s take a look at what’s new.

Next LTS :

After the version 5.1, the next Long Term Support release will be 5.5, which is expected to include two years of bug fixes and three years of security updates.

Laravel 5.5 will require PHP 7.0 :

PHP 7.0+ comes with lots of new developer features and speed improvement, which will considerably decrease the CPU load.

“vendor:publish” Gets a Prompt:

That means when you are running the command, now a prompt will ask you to select the provider or task. This gives the developer the liberty to publish only the ones that they need.

If you want to publish views, configs, migrations and other resources of all vendors, like the older version; you can use the “–all” or “–provider”  flags to bypass the prompt.

Fresh Migrations:

A new “migrate:fresh” Artisan command is being introduced. This is similar to the existing “migrate:refresh” option, however, rather than rolling back your existing migrations, it drops all tables and migrates them from start.

Streamlined Request Validation:

Laravel 5.5 will now let us create objects directly from the validated data which means you can pass the result directly to your model’s create or update methods.

It’s also possible to call validate on a request instance directly in Laravel 5.5.You also no longer need to pass the request as the first argument to the validator.


public function store()
{
$task = request()->validate([
'title' => 'required',
'body' => 'required'
]);

return Task::create($task);
}

Frontend Presets:

You may now configure the initial boilerplate as per your liking. Laravel 5.5 brings 3 front end preset options: Bootstrap, Vue, React with Vue being the default.

And you can strip all of it and if you want to remove any existing front-end scaffolding, you can use below command.

php artisan preset none

Automatic Package Discovery:

If you’ve ever installed a Laravel package before, you most certainly were required to visit your `config/app.php` file to add a service provider and alias. This is what allows the package to bootstrap itself into your Laravel installation. In Laravel 5.5, however, packages can optionally perform these steps automatically.

In Laravel 5.4 and all versions before, pulling a Laravel package required registering its service providers and adding aliases in `config/app.php`. In Laravel 5.5 packages can optionally perform these steps automatically and adds the ability for packages to automatically register service providers and add aliases through the package’s composer.json files.

And when a package is removed via Composer, then everything related to the package is also removed.

Faster Email Layout Testing:

In all the previous Laravel versions, we had to send actual emails or use an email client like Mailtrap to test email layouts. In Laravel 5.5, however, we can now return a mailable class instance directly from any route. very Convenient!

Custom Validation Rule:

In Laravel 5.5, you’ll find a brand new App/Rules folder. The next time you require custom logic for a particular request attribute, You can create a custom rule.

php artisan make:rule CustomRule

Collection Dumping:

Debugging a complex collection pipeline can get a little tricky. Often, you’ll find yourself temporarily commenting out portions of code, as you want to confirm the dumped output. In Laravel 5.5, you’ll find two new helper methods on your collection instances: dump() and dd().

$tasks = Task::all();

$tasks
->dump()
->sorBy(‘title’)
->dump()
->pluck(‘title’)
->dump();

This makes it easy to inspect the contents of the collection at each step. Note, however, that there’s a difference between calling dump() and dd() on a collection. dump() outputs the results at that moment and then continues processing while dd() stops the process immediately and dumps out the results

Model Factory Generation:

In Laravel 5.4, all model factories were contained within a single file. And when you want to construct a new factory then you need to copy and paste the one before it. Luckily in Laravel 5.5, there’s a simpler way. You can generate factory through below command and each of your Eloquent models will now have a respective model factory file.

php artisan make:factory TaskFactory

This will make a new file called TaskFactory.php in the database/factories folder. What even better is, you can also generate a factory while making a model.

Custom Blade “If” Directives:

If you are using repetitive checks within blade templates in your application then this feature will be very handy and clean. As now it is possible to abstract repetitive checks out of templates, leaving our templates looking cleaner and more readable. Checks like:

The logic for creating a custom blade directive goes inside the boot method of the AppServiceProvider class:


use Illuminate\Support\Facades\Blade;
.....
class AppServiceProvider extends ServiceProvider
{
....
public function boot()
{
Blade::if('subscribed', function () {
return auth()->check() && auth()->user()->isSubscribed();
});
}
....
}

Auto-Registering Artisan Commands:

In Laravel 5.5, you’ll no longer be required to manually register your Artisan commands, unlike all previous versions. The framework will instead automatically scan the commands folder for you. That means you may now run

php artisan make:command FooCommand,

and then immediately trigger it. very Useful.

Higher Order Tap:

tap() method was introduced in Laravel 5.3 and got some power boosts in 5.4. The tap() helper function has now been supercharged to be even more flexible.


return tap($task)->update([
'title' => $title,
'body' => $body,
]);

As we know Eloquent method update() and save() returns boolean value but with the use of tap() as above we can get task model with the output and then we can use that model in whatever way we like. very helpful.

The RefreshDatabase Trait:

In previous versions of Laravel, you were presented with two database-specific traits for your test classes: “DatabaseTransactions” and “DatabaseMigrations”. Sometimes it may be confusing to newcomers.

In Laravel 5.5, all of this has been streamlined. You’ll now find a single “RefreshDatabase” trait that automatically figures out automatically which DB reset strategy to use.

Please note though “DatabaseTransactions” and “DatabaseMigrations” traits are still available for backward compatibility.

Route Helpers:

In Laravel 5.5, two new helpful Route::view() and Route::redirect() is introduced. Think of these as shorthand for loading a view and performing a redirect, respectively.

Route::view('/welcome', 'welcome');

This route will map the welcome view to the /welcome path

Route::redirect('home', 'dashboard');

this route will redirect any requests made to /home to the /dashboard.

Toggle Exception Handling Within Your Tests:

When writing tests for your application, you may encounter situations when you don’t want Laravel to automatically catch and transform an exception. You can now disable exception handling on a test-by-test basis, via the $this->withoutExceptionHandling() method call.

Whoops is back:

Laravel 5.5 brings back “Whoops”- the error handling framework, which was used in version 4, and was removed from version 5.0. Whoops changes the appearance of the PHP exceptions.

In my opinion, error messages look better with this new handler and the fact that we get a screenshot with the line of code that resulted in the error makes debugging even easier As you can see in the image that it sports the lines of the file in which the error or exception occurred and traces back the operation till inception.

Cleaner Exception Rendering:

For previous Laravel versions, if we wanted to handle custom exceptions thrown in a specific way,  you had to check in the Handler class’s report or render method if a particular exception was thrown.

A more object-oriented approach would be to allow the exception to determine how to render itself.

In Laravel 5.5, A more object-oriented approach would be to allow the exception to determine how to render itself and it’s possible to specify what happens when a custom exception is thrown by creating a report() and render() method inside that exception class. very cleaner approach.

Other Misslanious changes:

One minor change is that if you forget to include the CSRF field in a form then it presents you with better inactivity error page. So, if you see something like that, then be sure that it’s related to CSRF.

There is another minor change that will help you in building APIs. Now you get a JSON stack trace rather than HTML markup if an error occurs. This makes it a lot prettier to look at rather than the ugly markup if you are using a tool like Postman.
Below are the few useful links, which will have all the latest features and improvements in Laravel 5.5

References/Resource:

Happy Learning!

Roadmap To Learn PHP & Laravel

Recently, I got an opportunity to train new joiners at the Cygnet Infotech. And I found this very helpful blog post related to that.

Roadmap To Learn PHP & Laravel

Thanks to  @introwit for the blog post.

This roadmap lists the complete course from step 1 to the end that will help a beginner learn PHP in the correct order right from scratch understanding almost all aspects of the language.

To be up to date with Laravel, you can follow top 15 Laravel Heros. You will learn many tips and tricks which will helpful into your day to day development.

If you are ever stuck somewhere while learning, hit me up on twitter at @solaniviral and I will be glad to help you.

Happy Learning!

Laravel : Best Practices

There are Many PHP Frameworks Available And I’ve worked with Zend, CakePHP, CodeIgniter then I picked up Laravel in 2014 and with version 4.2. Trust me, I totally love it now.

Speaking about Laravel, it is simple and comfortable to use, suitable to start with writing the production code, and gives a great boost to a development process. One thing that I love about Laravel is that it’s built using the best practices used in programming available in the current times.

Here are some simple things worth having in mind when developing in Laravel:

  • Try to make use of your .env file to the max you can.
  • Don’t create tables or index directly via PHPMyAdmin or console. Use Database Migration to create table, add/alter any fields, and commit those to Git repository.
  • Don’t insert fake values directly into the database for testing purposes. Create Seeder files or user Model Factory to populate your database.
  • Prefer to use Artisan CLI more than manually creating stuff, it’ll fasten up your productivity.
  • Make sure to boost performance using some artisan commands:
    php artisan route:cache
    php artisan config:cache
    php artisan optimize — force
  • Try not to write closures into your routes.php file, instead move them to your controller.
  • Use Named based Routing.
  • Be careful with the naming conventions when creating custom classes and functions, especially with your Models. Laravel works on a principle such that, for a table named users, it would expect it’s model name to be User.
  • Try to make Validation Requests separately for each request.
  • Although PHP has a class named DateTime to help you when reading, writing, comparing or calculating with date and time. It is recommended that you use the Carbon Library for dealing with dates.
  • Always keep yourself updated with the latest version, Laravel is updating real fast, so keep up the pace.
  • Always use gulp, Laravel Mix for compiling your scripts and sass into minified version for better performance, Laravel did the basic housekeeping for you.

Feel free to add more to the list…

How to replace plain URLs with links in JavaScript or PHP?

Hello Friends

If you want to convert plain text in to URLs in JavaScript or PHP. This is good solution for you.

In PHP :

public function makeLinks($str)
{
    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    $urls = array();
    $urlsToReplace = array();
    if(preg_match_all($reg_exUrl, $str, $urls)) {
        $numOfMatches = count($urls[0]);
        $numOfUrlsToReplace = 0;
        for($i=0; $i<$numOfMatches; $i++) {
            $alreadyAdded = false;
            $numOfUrlsToReplace = count($urlsToReplace);
            for($j=0; $j<$numOfUrlsToReplace; $j++) {
                if($urlsToReplace[$j] == $urls[0][$i]) {
                    $alreadyAdded = true;
                }
            }
            if(!$alreadyAdded) {
                array_push($urlsToReplace, $urls[0][$i]);
            }
        }
        $numOfUrlsToReplace = count($urlsToReplace);
        for($i=0; $i<$numOfUrlsToReplace; $i++) {
            $str = str_replace($urlsToReplace[$i], "<a target='_balnk' href=\"".$urlsToReplace[$i]."\">".$urlsToReplace[$i]."</a> ", $str);
        }
        return $str;
    } else {
        return $str;
    }
}

In JavaScript

function makeLinks(text) {
 var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
 return text.replace(exp,"<a target='_blank' href='$1'>$1</a>");
}

Hope it helps.

Set php.ini Values Using .htaccess

Did you know that you can set php.ini values right inside the .htaccess file? It’s actually very easy.

The .htaccess Code

#format
php_value setting_name setting_value#example
php_value  upload_max_filesize  10M

Of course you could simply place these in the .htaccess file, but .htaccess is a viable alternative if your host doesn’t allow you to touch the php.ini file.

Resource :

http://davidwalsh.name/php-values-htaccess

Prevent Your CSS and JavaScript Files From Being Cached

Some websites use highly volatile, oft-changing CSS and JavaScript files. In the case of these files, it’s important that the developer prevent browsers from caching them. How do we do that? By using a phantom querystring, of course. We’ll use PHP to tack the current time onto the file reference.

The PHP

<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" >
<-- RENDERS -->
<link href="/stylesheet.css?1234567890" rel="stylesheet" type="text/css">

<script type="text/javascript" src="/site-script.js?<?php echo time(); ?>"></script>
<-- RENDERS -->
<script type="text/javascript" src="/site-script.js?1234567890"></script>

It’s a very simple technique and doesn’t affect your CSS or JavaScript code in any way.

Resource :

http://davidwalsh.name/prevent-cache

Android Detection with JavaScript or PHP

Hello Friends

You have a web application and you want to detect that if your Application is opened from android device than it will be redirect to any other URL that will be Android compatible.This is a good solution for you.

What’s obvious is that Android development is a hot topic that will only grow. Here are a few methods by which you can detect iOS‘ main competitor: Android.

The JavaScript

Searching the user agent string for “Android” is the quickest method:

var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid)
{
// Do something! // Redirect to Android-site? window.location = 'http://android.viralsolani.co';
}

The PHP

Again, we’ll use PHP’s strstr function to search for Android in the user agent:

$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false){// && stripos($ua,'mobile') !== false) {
header('Location: http://android.viralsolani.co');
exit();
}

Bonus! .htaccess Detection

We can even use .htaccess directives to detect and react to Android devices!

RewriteCond %{HTTP_USER_AGENT} ^.*Android.*$
 RewriteRule ^(.*)$ http://android.viralsolani.co [R=301]

And there you have it: three different Android device detection! Have fun with your mobile development!

Resource :

http://davidwalsh.name/detect-android

Thanks

 

PHP SDK & Graph API base Facebook Connect Tutorial

Hello Friends

In My current application I’ve used facebook Graph API to fetched data from facebook with the help of  PHP SDK. I’ve explored so many tutorials on web but I found some links are very helpful and easy to understand Here I’m sharing those links. By surfing through these links you can get to know these below things

1 . How you can create your application in Facebook and How you can use APP ID and APP Secret? 

2. How you can connect to Facebook from your Application?

3. How you can fetch data with the help of Facebook Graph API and PHP-SDK?

4. How you can Design your Facebook Application?

So here are some useful links.

  1. http://www.londatiga.net/it/how-to-create-facebook-application-with-php-for-beginner/
  2. http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/
  3. http://net.tutsplus.com/tutorials/php/wrangling-with-the-facebook-graph-api/
  4. http://www.joeyrivera.com/2010/facebook-graph-api-app-easy-w-php-sdk/
  5. http://net.tutsplus.com/tutorials/javascript-ajax/design-and-code-an-integrated-facebook-app/

To Create a New Application in Facebook.

https://developers.facebook.com/apps

Graph API

https://developers.facebook.com/docs/reference/api/

PHP SDK refrence

https://developers.facebook.com/docs/reference/php/

FB Tool for Graph API Explorer

http://developers.facebook.com/tools/explorer

Hope it helps.


profile for Viral Solani at Stack Overflow, Q&A for professional and enthusiast programmers

How to Install Apache, PHP, MySQL and PHPMyAdmin in Ubuntu 11.04

If you are a PHP based web developer, you need all the software running and configured properly. Here I am talking about installing them One by One in your Ubuntu Desktop. We are installing all the applications from terminal.

How to Open Terminal:
So, to fire up the terminal follow any of these steps:

  1. If you are running Unity Desktop, click on the Ubuntu Logo at top left corner and type Terminal in the search application bar. Then click on the terminal icon.
  2. If you are running GNome Desktop, click on Applications->Accessories->Terminal
  3. For shortcut, you can also press Ctrl+Alt+T at once, to open the terminal.

How to install Apache:

1. Make sure you have the internet connection. To install apache execute the following command in the terminal:

1
sudo apt-get install apache2

It takes some time to download and install apache. After the setup completes, type http://localhost/ in your browser window to make sure apache is installed and running properly. If you see the page with It Works!, the setup of apache2 completes successfully.

How to Install PHP:

1. To install PHP 5, type following commands in the terminal one by one:

1
2
sudo apt-get install php5
sudo apt-get install libapache2-mod-php5

The first line installs PHP5 in the computer. The second one provides the PHP5 module for the Apache 2 webserver. If second one is not installed, then Apache cannot parse PHP codes in a web page.

2. After installing PHP5 and PHP module for apache, restart the apache with following code:

1
sudo /etc/init.d/apache2 restart

3. While restarting the apache server, if you see a warning as “Could not reliably determine the server’s fully qualified domain name, using 127.0.1.1 for ServerName”, then you can fix this by creating a file with the Server name. To do this type the following command in the terminal:

1
sudo gedit /etc/apache2/conf.d/fqdn

When the text editor opens, type “ServerName localhost” inside the file and click Save. Then close it. Now restart again with the above code and you will see that the warning message has gone.

4. Now, we have successfully installed php and apache web server. However, still we don’t know if PHP is successfully installed. To check this, create a file inside /var/www/ folder named test.php as:

1
sudo gedit /var/www/test.php

and write following code in it

1
<?php   phpinfo();  ?>

Save the file and type this in browser: http://localhost/test.php

If you see the various information about PHP and installed modules there, then we can confirm that Apache is parsing PHP codes. Hence the installation is successful up to this point.

How to Install MySQL:

1. To install MySQL Server in ubuntu, type following code in terminal window:

1
sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql

This will install latest mysql server and other necessary PHP modules for recognizing mysql functions from PHP code. While installing MySQL server, you may require to enter the password for MySQL root user.

How to Install PHPMyAdmin:

1. To Install PHPMyAdmin, type the following codes in the terminal:

1
sudo apt-get install phpmyadmin

While installing PHPMyAdmin, you may require to select the web server. In such case, tick the Apache2 Server and proceed with the installation. You may also require to input MySQL root user password during installation.

Once the installation completes, type this in your browser window to confirm the successful installation of PHPMyAdmin: http://localhost/phpmyadmin/index.php.

Now, you are finished. Your environment is setup and you can enjoy using all these applications. Next, you can install other applications that may be necessary such as Eclipse, GIMP etc.

The Right Way to Get a File Extension in PHP

I made a recent search on retrieving file extensions in PHP.

I found out that a lot have been re-inventing the wheel. They have been creating code for functionality that PHP already has. This is one example of re-inventing the wheel

function get_file_extension($file_name)
{
return substr(strrchr($file_name,’.’),1);
}

Another example was this:

function file_extension($filename)
{
return end(explode(“.”, $filename));
}

PHP already has a function that does the same thing and more.

Welcome, pathinfo.

$file_path = pathinfo(‘/www/htdocs/your_image.jpg’);
echo “$file_path [‘dirname’]\n”;
echo “$file_path [‘basename’]\n”;
echo “$file_path [‘extension’]\n”;
echo “$file_path [‘filename’]\n”; // only in PHP 5.2+


// Output
/www/htdocs
your_image.jpg
jpg
your_image

A much easier way to use the constants:
[PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME]

PATHINFO_DIRNAME – the directory
PATHINFO_BASENAME – the file name
PATHINFO_EXTENSION – the extension
PATHINFO_FILENAME – the filename without the extension

echo pathinfo(‘/www/htdocs/your_image.jpg’, PATHINFO_EXTENSION);

// Output

jpg