Tuesday, 7 November 2017

Laravel 5.5 Gets Improvements with the Default Error Views

Coming in Laravel 5.5 is a new and improved design for the error pages. The default errors will extend from an errors::layout file and get some small design additions over the current style with flexbox and a vertically centered message.
Here is how the current 50* error page looks in Laravel 5.4:
Coming to Laravel 5.5 is a new modern design:

Customizing the Laravel Error Messages

Just as before you can still easily customize the Laravel error views by creating your own in the resources/views/errors* directory. It works by naming your Blade file the same as the error number. So if you want to have a custom 500 page, then you would create resources/views/errors/500.blade.php.
Inside this template, you can adjust the following sections:
@extends('errors::layout')

@section('title', 'Error')

@section('message', 'Sorry, we are having a temporary problem. We have been alerted and will be rolling out a fix soon')
The parent errors::layout comes from inside the framework and you are welcome to continue using it, or create your layout file and extend it.
By default, Laravel comes with the following included error files:
  • 404.blade.php
  • 419.blade.php
  • 500.blade.php
  • 503.blade.php
Finally, if you are curious on how Laravel determines the error view file to show the user take a look at the renderHttpException method.
The first main part is the replaceNamespace call which says to first look in your “resources/views” folder, then fallback to the “views” within the framework:
view()->replaceNamespace('errors', [
    resource_path('views/errors'),
    __DIR__.'/views',
]);
Then it returns the view of the status code if it exists:
return response()->view("errors::{$status}"
As a side note, this same fallback pattern can be setup in your views by adding additional paths to your “config/views.php” file.
'paths' => [
    realpath(base_path('resources/views/new-design')),
    realpath(base_path('resources/views')),
],
Now Laravel will look for a template file in the “new-design” folder and use it if it’s found, otherwise, it’ll use it from the “views” folder.

Validator::extend for custom validation rules laravel 5.5

Laravel 5.5 will introduce support for custom validation rule objects as an alternative to using Validator::extend for custom validation rules.
To define a custom validation rule, implement the Illuminate\Contracts\Validation\Rule interface or use a Closure. The custom rule is then used directly in a validator.
An example of a custom object validation rule might look something like:
use Illuminate\Contracts\Validation\Rule;

class CowbellValidationRule implements Rule
{
    public function passes($attribute, $value)
    {
        return $value > 10;
    }

    public function message()
    {
        return ':attribute needs more cowbell!';
    }
}
With the custom rule defined, you might use it in your controller validation like so:
public function store()
{
    // Validation message would be "song needs more cowbell!"
    $this->validate(request(), [
        'song' => [new CowbellValidationRule]
    ]);
}
The same rule as a Closure would look something like the following.
public function store()
{
    $this->validate(request(), [
        'song' => [function ($attribute, $value, $fail) {
            if ($value <= 10) {
                $fail(':attribute needs more cowbell!');
            }
        }]
    ]);
}
The custom rule examples will not run if the song field is empty or isn’t present in the request. If you want a custom validation object to run even with the value is empty, you need to use the ImplicitRule contract.
use Illuminate\Contracts\Validation\ImplicitRule;

class CowbellValidationRule implements ImplicitRule
{
    public function passes($attribute, $value)
    {
        return $value > 10;
    }

    public function message()
    {
        return ':attribute needs more cowbell!';
    }
}
Custom validation rule objects will be an excellent alternative to Validator::extend() style custom rules if you prefer to organize custom rules in classes. Also, jumping to the rule source code from a validator can be more convenient than searching for a custom string-based rule defined with Validator::extend.
The Closure style custom validation rules will be nice for simple one-off needs and make it really convenient to experiment with custom validation rules without leaving the controller. You could use a Closure to experiment with a custom rule and then move it to an object if the rule proves useful.
Check out the pull request files to see how this feature was implemented and tested.

Laravel 5.5 new feature pivot table casts

A new addition to Laravel 5.5 will add support for pivot table casts when inserting & updating data on an intermediate table model.
Currently, the $casts you set on a traditional model will work in both directions; any model that extends the Eloquent\Model class will look for a $casts property and convert the specified attributes to a data type when reading and writing. For example, from the documentation:
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
    * The attributes that should be cast to native types.
    * @var array
    */
    protected $casts = [
        'is_admin' => 'boolean',
    ];
}
In Laravel 5.4, Taylor added the ability to define a $casts property on your custom pivot models as well, but it only applied those $casts when reading the data—no conversion was performed when inserting or updating an attribute.
For example, let’s say you have a Runner model and a Race model. One runner can have many races, and one race can have many runners. Let’s call our pivot model a RaceRunner, which will include a splits array with a varying number of individual lap times (depending on the length of the race, and stored in seconds) in addition to the required runner_id and race_id.
The splits array is serialized as JSON in the race_runner table, so if you defined splits as an array in the $casts of your RaceRunner pivot model, then the following will dump an array:
dd( $runner->pivot->splits );

// Example:
[
    'Lap 1' => 150,
    'Lap 2' => 163,
    'Lap 3' => 146
]
But when creating or updating the pivot model, you still have to cast it manually:
// Cast first...
$splits = $splits->toJson();

// ...then attach:
$runner->races()->attach($raceId, ['splits' => $splits]);
Now with Laravel 5.5, the $casts property on the Eloquent\Model and Eloquent\Relations\Pivot classes will behave the same. Laravel will “respect” your casts on both, whether you’re reading, inserting or updating data. This will make the attach, sync and save methods available to pivot models. Applying this new feature to our example above, the // Cast first... code is no longer necessary.

source:https://laravel-news.com

Monday, 6 November 2017

Blade with View::first new Features in Laravel5.5

When building dynamic components or pages sometimes we want to display a custom template if it exists or otherwise falls back on a default one.
We can solve this problem with a series of conditionals or by using view()->exists() to check if a custom template exists or not, however, Laravel 5.5 brings us a better and more elegant way as I’ll demonstrate in the following video:
https://www.youtube.com/watch?v=n32SwdlvAPI

Using View:: first

The view()->first() method allows us to replace the following code:
if (view()->exists('template1')) {
    return view('template1', $data);
}

return view('1template2', $data);
With a simpler, more expressive version:
return view()->first(
    ['template1', 'template2'], $data
);
You have to pass an array of templates as the first argument and the first method will load the first template it finds.
Of course, you can pass as many templates as you want and even use dynamic names:
return view()->first([
    "pages/{$page->slug}",
    "pages/category-{$page->category->slug}",
    "pages/default-template"
], $data);
Remember you can also use this feature using its facade version:
\View::first($templates, $data)
This dynamic view loading feature was added to Blade in Laravel v5.5 and is a great way of keeping your controllers simple by avoiding extra conditionals when dealing with dynamic templates.

Sunday, 5 November 2017

Laravel new Features in Blade If Directives

A new Blade addition in Laravel 5.5 will add support for simplifying custom ifstatements in your views.
The syntax might something like this in your AppServiceProvider::boot()method:
use Illuminate\Support\Facades\Blade;

Blade::if('admin', function () {
    return auth()->check() && auth()->user()->isAdmin();
});
The new Blade::if() makes it convenient to abstract repetitive checks out of templates, making them more readable:
@admin
    <a href="{{ route('super.secret') }}">Secret Page</a>
@else
    Welcome Guest. <a href="{{ route('login') }}">Login</a>
@endadmin
In previous versions of Laravel, you would have to write a bit more code. For example, David Hemphill tweeted some really cool directives using this technique in Laravel 5.4:
//AppServiceProvide
Blade::directive('prod',function($beta){
 return "<?php if(app()->environment('production')):?>";
});
Blade::directive('endprod',function($beta){
 return "<?php endif; ?>";
});

-----------------------------------
//In your blade template
@prod
<script src="some-production-only-script" async></script>
@endprod
Which is now simplified even more in Laravel 5.5:
Blade::if('prod', function () {
    return app()->environment('production');
});
You can also pass arguments to make the checks more dynamic:
Blade::if('env', function ($env) {
    return app()->environment($env);
});
Which would then look like this in your templates:
@env('production')
  <script src="some-prod.js"></script>
@endenv
If you want to learn more about Blade::if(), Laracasts has a video tutorial on it, and we look forward to seeing what you’ll come up with!

A look at Laravel Horizon

The moment everyone in the Laravel community has been waiting for has finally arrived! Laravel Horizon is software to “supercharge your queues with a beautiful dashboard and code-driven configuration.”
On a regular basis, I find myself on a production server console trying to rerun failed jobs and clear a “stuck” jobs and using redis-cli see what is in the queue. Generally speaking, Laravel queues are amazing and work fantastically most of the time; however, when things fail, troubleshooting queues can be a daunting task. On top of troubleshooting, wouldn’t you also like some key metrics on queue performance?
Laravel Horizon is designed to make it easy monitor your queues from a web interface and receive notifications when things go wrong.
According to Taylor Otwell, the creator of Laravel, here’s the background of why he built Laravel Horizon:
I built Horizon to scratch my own itch. I need deep insight into my queue throughput, performance, wait times, failures. And, when a customer has a problem, Horizon allows me to quickly find the job that failed.

Key Features

At a high level, here are some of the key features of Laravel Horizon:
  • Auto-balancing
  • Code-Driven Configuration
  • Dashboards and Metrics
  • Queue monitoring
  • Failed Job Management
  • Notifications
  • Open-Source Software

Auto-balancing

Horizon will balance your workers across queues. When a queue gets busy, Horizon can intelligently see if any other workers are available and move them to queues that need help.

Code-Driven Configuration

Laravel Horizon uses code-driven configuration, which is awesome because you can version control it along with your project.

Dashboard Metrics

See what your queue is doing in real-time with dashboard metrics for your queues and jobs. The metrics can help you monitor things like performance, job stats, and throughput.

Queue Monitoring

With Laravel Horizon you will be able to tag your jobs and monitor them with a simple dashboard. Monitoring will allow you to isolate issues and usage patterns according to your specific needs.

Failed Job Management

Most people that have used Laravel queues have had to SSH into a server and retry failed queue jobs. Laravel Horizon will make it easy to retry failed jobs and even search failed jobs and retry specific jobs. For example, you can search for a failed jobs for a single user and retry them.

Notifications

When a queue is getting overloaded, Laravel Horizon can notify you of the issue, allowing you to react much more quickly. I’ve set up custom monitoring in order to receive queue notifications when things go bad, but Laravel Horizon should make it much simpler to get notifications up without all the hassle of setting up custom monitoring solutions.

Open Source

In my opinion, one of the most awesome parts of Laravel Horizon is that the free version will be 100% open-source software. You will be able to browse the source code and contribute if you run into a bug or spot an improvement that can be made.

Conclusion

Laravel Horizon is an exciting addition to the Laravel ecosystem and solves a much-needed pain point around using queues with Laravel. I personally can’t wait to install Horizon and give it a further review after launching it into one of my production systems!
source: https://laravel-news.com

Laravel new Features in Routing methods in laravel

Laravel 5.5 shipped a couple of convenient shortcuts to the Laravel Router class that eliminates the need for creating a controller or closure only to return a simple view or redirect.

1. Route::view
2. Route::redirect

Here we will see clear information regarding route functions.


The Route::view method

The Route::view method eliminates the need for routes that only need a view returned. Instead of using a controller or a closure, you can define a URI and a path to a view file:


// resources/views/pages/about.blade.php
Route::view('/about', 'pages.about');
You can also pass in an array of variables that will be passed to the view:
Route::view('/about', 'pages.about', ['year' => date('Y')]);
The Route::redirect Method


The Route::redirect method also eliminates the need to create a controller or a closure only to return a redirect response:
Route::redirect('/homepage', '/home');
The third default argument, if not passed, is a 301 redirect. However, you can pass the third argument for a different status code. For example, if you want to create a 307 Temporary Redirect, it would look like this:
Route::redirect('/homepage', '/home', 307);

cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in Laravel

  WampServer: Download this file:  http://curl.haxx.se/ca/cacert.pem Place this file in the  C:\wamp64\bin\php\php7.1.9  folder Open  php.in...

Popular Articles