Content Source:
How to develop multi tenant application using Laravel
If you want to run multiple websites using the same Laravel installation while keeping tenant specific data separated for fully independent multi-domain setups then it is pretty easily possible with this multi-tenant Laravel package.
With this package, you can serve multiple websites each with one or more hostnames from the same codebase. It has clear separation of database, assets & it also provides the ability to override logic per tenant.
This is suitable for marketing companies or startups which are building Software as a Service(SaaS).
I know this architecture is opposite to famous micro-service architecture, but just posting it in case someone is in the need to do so.
This package offers following features under the hood:
- Integration with the awesome Laravel framework.
- Event driven, extensible architecture.
- Close – optional – integration into the web server.
- The ability to add tenant specific configs, code, routes etc.
Database separation methods:
- One system database and separated tenant databases (default).
- Table prefixed in the system database.
- Or manually, the way you want, by listening to an event.
Requirements, recommended environment:
- Latest stable and LTS Laravel versions.
- PHP 7+.
- Apache or Nginx.
- MySQL, MariaDB or PostgreSQL.
Installation
composer require hyn/multi-tenant
Automatic service registration
Using auto discovery, the tenancy package will be auto detected by Laravel automatically.
Manual service registration
In case you want to disable webserver integration or prefer manual integration, set the dont-discover
in your application composer.json, like so:
{ "extra": { "laravel": { "dont-discover": [ "hyn/multi-tenant" ] } } }
If you disable auto-discovery you are able to configure the providers by yourself.
Register the service provider in your config/app.php:
'providers' => [ // [..] // Hyn multi tenancy. Hyn\Tenancy\Providers\TenancyProvider::class, // Hyn multi tenancy webserver integration. Hyn\Tenancy\Providers\WebserverProvider::class, ],
Deploy configuration
First publish the configuration and migration files so you can modify it to your needs:
php artisan vendor:publish --tag tenancy
Open the config/tenancy.php
and config/webserver.php
file and modify to your needs.
Make sure your system connection has been configured in database.php
. In case you didn’t override the system connection name the default
connection is used.
Now run:
php artisan migrate --database=system
This will run the required system database migrations.
Testing
Run tests using:
vendor/bin/phpunit
If using MySQL, use:
LIMIT_UUID_LENGTH_32=1 vendor/bin/phpunit
Please be warned running tests will reset your current application completely, dropping tenant and system databases and removing the tenancy.json file inside the Laravel directory.
For more Information and to build a website using Laravel, Hire Laravel Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.To develop the custom website using Laravel, please visit our technology page
- fullstackworld.com/
- github.com/tenancy/multi-tenant
Automate Future Notifications and Reminders with Laravel Snooze
Laravel Snooze is a package, which simplifies automating future notifications and reminders in Laravel.
The package’s readme has some typical use-cases for this package:
- Reminder system (1 week before appt, 1 day before, 1 hour before, etc)
- Follow-up surveys (2 days after purchase)
- On-boarding Email Drips (Welcome email after sign-up, additional tips after 3 days, upsell offer after 7 days)
- Short-Term Recurring reports (send every week for the next 4 weeks)
Why use this package?
- Ever wanted to schedule a future notification to go out at a specific time? (was the delayed queue option not enough?)
- Want a simple on-boarding email drip?
- How about happy birthday emails?
Common use cases
- Reminder system (1 week before appt, 1 day before, 1 hour before, etc)
- Follow-up surveys (2 days after purchase)
- On-boarding Email Drips (Welcome email after sign-up, additional tips after 3 days, upsell offer after 7 days)
Short-Term Recurring reports (send every week for the next 4 weeks)
Installation
- Install via composer
- composer require thomasjohnkane/snooze
- php artisan migrate
Publish Configuration File
php artisan vendor:publish --provider="Thomasjohnkane\Snooze\ServiceProvider" --tag="config"
Usage
Using the model trait
Snooze provides a trait for your model, similar to the standard Notifiable trait. It adds a notifyAt()
method to your model to schedule notifications.
use Thomasjohnkane\Snooze\Traits\SnoozeNotifiable; class User extends Model { use SnoozeNotifiable; // ... } // Schedule a birthday notification $user->notifyAt(new BirthdayNotification, Carbon::parse($user->birthday)); // Schedule for a week from now $user->notifyAt(new NextWeekNotification, Carbon::now()->addDays(7)); // Schedule for new years eve $user->notifyAt(new NewYearNotification, Carbon::parse('last day of this year'));
Using the ScheduledNotification::create helper
You can also use the create method on the ScheduledNotification.
ScheduledNotification::create( Auth::user(), // Target new ScheduledNotificationExample($order), // Notification Carbon::now()->addHour() // Send At ); This is also useful for scheduling anonymous notifications (routed direct, rather than on a model). $target = (new AnonymousNotifiable) ->route('mail', 'hello@example.com') ->route('sms', '56546456566'); ScheduledNotification::create( $target, // Target new ScheduledNotificationExample($order), // Notification Carbon::now()->addDay() // Send At );
An important note about scheduling the snooze:send command
Creating a scheduled notification will add the notification to the database. It will be sent by running snooze:send
command at (or after) the stored sendAt
time.
The snooze:send
command is scheduled to run every minute by default. You can change this value (sendFrequency)
in the published config file. Available options are everyMinute
, everyFiveMinutes
, everyTenMinutes
, everyFifteenMinutes
, everyThirtyMinutes
, hourly
, and daily
.
The only thing you need to do is make sure schedule:run
is also running. You can test this by running php artisan schedule:run
in the console.
Setting the send tolerance
If your scheduler stops working, a backlog of scheduled notifications will build up. To prevent users receiving all of the old scheduled notifications at once, the command will only send mail within the configured tolerance. By default this is set to 24 hours, so only mail scheduled to be sent within that window will be sent. This can be configured in the snooze.php
config file.
Cancelling Scheduled Notifications
$notification->cancel();
Note: you cannot cancel a notification that has already been sent.
Rescheduling Scheduled Notifications
$rescheduleAt = Carbon::now()->addDay(1)
$notification->reschedule($rescheduleAt)
Note: you cannot reschedule a notification that has already been sent or cancelled. If you want to duplicate a notification that has already been sent or cancelled, pass a truthy second parameter along with the new send date; reschedule($date, true)
, or use the scheduleAgainAt($date)
method shown below
Duplicate a Scheduled Notification to be sent again
$notification->scheduleAgainAt($newDate);
Check a scheduled notification’s status
// Check if a notification is already cancelled $result = $notification->isCancelled(); // returns a bool // Check if a notification is already sent $result = $notification->isSent(); // returns a bool
Conditionally interrupt a scheduled notification
If you’d like to stop an email from being sent conditionally, you can add the shouldInterrupt()
method to any notification. This method will be checked immediately before the notification is sent.
For example, you might not send a future drip notification if a user has become inactive, or the order the notification was for has been canceled.
public function shouldInterrupt($notifiable) { return $notifiable->isInactive() || $this->order->isCanceled(); }
If this method is not present on your notification, the notification will not be interrupted. Consider creating a shouldInterupt trait if you’d like to repeat conditional logic on groups of notifications.
Running the Tests
composer test
To develop the custom website using Laravel, please visit our technology page
Content Source:
- laravel-news.com
Laravel: Fail, Retry, or Delay a queued job from itself
When creating jobs, listeners, or subscribers to push into the queue, you may start thinking that, once dispatched, you’re all on your own with what the queue worker decides to do with your logic.
Well, it’s not that you can’t interact with the queue worker from inside the job, but you usually don’t need to… until you do.
The magic happens because of the InteractsWithQueue
trait. When the queued job is being pulled out from the queue, the CallQueuedListener
will check if it’s using the InteractsWithQueue
trait, and if it is, the framework will inject the underlying “job” instance inside.
This “job” instance is like the driver that wraps your real Job
class, which contains information about the connection and attempts, among other things.
Context
We will use a transcoding Job
as an example. This is a job that transcodes a podcast audio file into an MP3 of 192kbps. Because this is set in the free transcoding queue, it has limited availability.
Checking the Attempts
The first method is called attempts()
, and as its name implies, it returns the number of attempts. A Job
always starts with one attempt.
This method is meant to be used with others, like fail()
or release()
(delay). For illustration purposes, we will notify the user of the nth retrying: each time we try to transcode a podcast in the free queue, we will notify the user we’re retrying for the nth time, giving him the option to cancel future transcodes.
<?php namespace App\Jobs; use App\Podcast; use Transcoder\Transcoder; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use App\Notifications\PodcastTranscoded; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Foundation\Bus\Dispatchable; use App\Notifications\RetyingPodcastTranscode; class TranscodePodcast { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Transcoder Instance * * @var \App\Podcast */ protected $podcast; /** * Create a new Transcode Podcast instance. * * @param \App\Podcast $podcast * @return void */ public function __construct(Podcast $podcast) { $this->podcast = $podcast; } /** * Execute the job. * * @param \Transcoder\Transcoder $podcast * @return void */ public function handle(Transcoder $transcoder) { // Tell the user we're retrying for the nth time if ($this->attempts() > 1) { $this->podcast->publisher->notify(new RetryingPodcastTranscode($this->podcast, $this->attempts()); } $transcoded = $this->transcoder->setFile($event->podcast) ->format('mp3') ->bitrate(192) ->start(); // Associate the transcoded podcast to the original podcast. $this->podcast->transcode()->associate($transcoded); // Notify the publisher of the podcast that his podcast is ready $this->publisher->notify(new PodcastTranscoded($this->podcast)); } }
Telling the user that we’re retrying something for the nth time is useful when the logic has failed beforehand, letting the user (or developer) check what went wrong, but of course you can do more than that.
Personally, we like to do that after the Job
failed, and if it has retries left, tell him that we’re going to retry later.
Deleting the Job
The second method is delete()
. As you can guess, you can delete the current Job
from the queue.
This can be handy when you shouldn’t process the job or listener after it was queued for several reasons. For example, think about this scenario: the publisher that uploaded the podcast has been deactivated for any reason (like a TOS violation) before the transcoding occurs, and we should not process the podcast.
We will add that code to the example from before:
<?php namespace App\Jobs; use App\Podcast; use Transcoder\Transcoder; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use App\Notifications\PodcastTranscoded; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Foundation\Bus\Dispatchable; use App\Notifications\RetyingPodcastTranscode; class TranscodePodcast { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Transcoder Instance * * @var \App\Podcast */ protected $podcast; /** * Create a new Transcode Podcast instance. * * @param \App\Podcast $podcast * @return void */ public function __construct(Podcast $podcast) { $this->podcast = $podcast; } /** * Execute the job. * * @param \Transcoder\Transcoder $podcast * @return void */ public function handle(Transcoder $transcoder) { // If the publisher has been deactivated, take this job out if ($this->podcast->publisher->isDeactivated()) { $this->delete(); } // Tell the user we're retrying for the nth time if ($this->attempts() > 1) { $this->podcast->publisher->notify(new RetryingPodcastTranscode($this->podcast, $this->attempts()); } $transcoded = $this->transcoder->setFile($event->podcast) ->format('mp3') ->bitrate(192) ->start(); // Associate the transcoded podcast to the original podcast. $this->podcast->transcode()->associate($transcoded); // Notify the publisher of the podcast that his podcast is ready $this->publisher->notify(new PodcastTranscoded($this->podcast)); } }
If you need to delete the job on models that may have been deleted, you may want to set $deleteWhenMissingModels
to true to avoid processing something that is not there.
Failing the Job
This is very, very handy when you need control over artificially failing the logic, because using an empty return
statement will mark the Job as done successfully. You can forcefully fail the queued job
, hopefully with an exception, allowing the handler to retry it later if possible.
This gives you finer control when the job fails. In any case, you can also use the failed()
method, which allows you to perform any cleaning after it fails, like notifying the user or deleting something.
In this example, we will fail the job if the podcast cannot be retrieved from storage for whatever reason, like when the CDN goes down, throwing a custom exception.
<?php namespace App\Jobs; use App\Podcast; use Transcoder\Transcoder; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use App\Exceptions\PodcastUnretrievable; use App\Notifications\PodcastTranscoded; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Foundation\Bus\Dispatchable; use App\Notifications\RetyingPodcastTranscode; class TranscodePodcast { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Transcoder Instance * * @var \App\Podcast */ protected $podcast; /** * Create a new Transcode Podcast instance. * * @param \App\Podcast $podcast * @return void */ public function __construct(Podcast $podcast) { $this->podcast = $podcast; } /** * Execute the job. * * @param \Transcoder\Transcoder $podcast * @return void */ public function handle(Transcoder $transcoder) { // If the publisher has been deactivated, take this job out if ($this->podcast->publisher->isDeactivated()) { $this->delete(); } // If the podcast cannot be retrieved from the storage, we will fail miserably. if ($this->podcast->fileDoesntExists()) { $this->fail(new PodcastUnretrievable($this->podcast)); } // Tell the user we're retrying for the nth time if ($this->attempts() > 1) { $this->podcast->publisher->notify(new RetryingPodcastTranscode($this->podcast, $this->attempts()); } $transcoded = $this->transcoder->setFile($event->podcast) ->format('mp3') ->bitrate(192) ->start(); // Associate the transcoded podcast to the original podcast. $this->podcast->transcode()->associate($transcoded); // Notify the publisher of the podcast that his podcast is ready $this->publisher->notify(new PodcastTranscoded($this->podcast)); } }
Releasing (Delaying) a Job
This is probably the most useful method of the trait, as it allows you to push the job further into the future. This method is used for rate limiting your job.
Apart from rate limiting, you can also use this when something is not available but you expect it to be in the near future. Also, to avoid failing preemptively.
In this last example, we will delay the transcoding for later: if the transcoder is under heavy usage, we will delay the transcoding for five minutes until the load lowers.
<?php namespace App\Jobs; use App\Podcast; use Transcoder\Transcoder; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use App\Exceptions\PodcastUnretrievable; use App\Notifications\PodcastTranscoded; use Illuminate\Queue\InteractsWithQueue; use App\Notifications\TranscoderHighUsage; use Illuminate\Foundation\Bus\Dispatchable; use App\Notifications\RetyingPodcastTranscode; class TranscodePodcast { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Transcoder Instance * * @var \App\Podcast */ protected $podcast; /** * Create a new Transcode Podcast instance. * * @param \App\Podcast $podcast * @return void */ public function __construct(Podcast $podcast) { $this->podcast = $podcast; } /** * Execute the job. * * @param \Transcoder\Transcoder $podcast * @return void */ public function handle(Transcoder $transcoder) { // If the publisher has been deactivated, take this job out if ($this->podcast->publisher->isDeactivated()) { $this->delete(); } // If the podcast cannot be retrieved from the storage, we will fail miserably. if ($this->podcast->fileDoesntExists()) { $this->fail(new PodcastUnretrievable($this->podcast)); } // If the Transcoder usage is high, we will avoid choking it by delaying the // transcoding by 5 minutes. Otherwise we may risk stalling the transcoder // process, which will take down all transcoding sub-processes with him. if ($transcoder->getLoad()->isHigh()) { $delay = 60 * 5; $this->podcast->publisher->notify(new TranscoderHighUsage($this->podcast, $delay)); $this->release($delay); } // Tell the user we're retrying for the nth time if ($this->attempts() > 1) { $this->podcast->publisher->notify(new RetryingPodcastTranscode($this->podcast, $this->attempts()); } $transcoded = $this->transcoder->setFile($event->podcast) ->format('mp3') ->bitrate(192) ->start(); // Associate the transcoded podcast to the original podcast. $this->podcast->transcode()->associate($transcoded); // Notify the publisher of the podcast that his podcast is ready $this->publisher->notify(new PodcastTranscoded($this->podcast)); } }
We could use some magic, for example, getting assign some slots to the transcoder, and delay the job if the transcoder slots are full.
And that’s pretty much all you can do from inside the queued job.
For more Information and to build a website using Laravel, Hire Laravel Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop the custom website using Laravel, please visit our technology page
Content Source:
- medium.com
Amazing Features and Updates of Laravel 6
Laravel 6 release includes compatibility with Laravel Vapor, improved authorization responses, job middleware, lazy collections, sub-query improvements, semantic versioning, among many other improvements.
Here are some of the new features included in Laravel 6:
Semantic Versioning
The Laravel framework (laravel/framework) package now follows the semantic versioning standard. This makes the framework consistent with the other first-party Laravel packages which already followed this versioning standard. The Laravel release cycle will remain unchanged.
Laravel Vapor Compatibility
Laravel 6.0 provides compatibility with Laravel Vapor, an auto-scaling serverless deployment platform for Laravel. Vapor abstracts the complexity of managing Laravel applications on AWS Lambda, as well as interfacing those applications with SQS queues, databases, Redis clusters, networks, CloudFront CDN, and more.
Improved Exceptions Via Ignition
Laravel 6.0 ships with Ignition, a new open source exception detail page created by Freek Van der Herten and Marcel Pociot. Ignition offers many benefits over previous releases, such as improved Blade error file and line number handling, runnable solutions for common problems, code editing, exception sharing, and an improved UX.
Improved Authorization Responses
In previous releases of Laravel, it was difficult to retrieve and expose custom authorization messages to end users. This made it difficult to explain to end-users exactly why a particular request was denied. In Laravel 6.0, this is now much easier using authorization response messages and the new Gate::inspect
method. For example, given the following policy method:
/** * Determine if the user can view the given flight. * * @param \App\User $user * @param \App\Flight $flight * @return mixed */ public function view(User $user, Flight $flight) { return $this->deny('Explanation of denial.'); }
The authorization policy’s response and message may be easily retrieved using the Gate::inspect
method:
$response = Gate::inspect('view', $flight); if ($response->allowed()) { // User is authorized to view the flight... } if ($response->denied()) { echo $response->message(); }
In addition, these custom messages will automatically be returned to your frontend when using helper methods such as $this->authorize
or Gate::authorize
from your routes or controllers.
Job Middleware
Job middleware allow you wrap custom logic around the execution of queued jobs, reducing boilerplate in the jobs themselves. For example, in previous releases of Laravel, you may have wrapped the logic of a job’s handle
method within a rate-limited responsibilities.
You define middleware by specifying a middleware()
method on the job class which returns an array of middleware objects. From the pull request, here’s an example:
public function middleware() { return [new SomeMiddleware]; }
And here’s an example of the middleware class:
class SomeMiddleware { public function handle($command, $next) { // Do something... return $next($command); } }
You can also specify middleware when dispatching a job:
SomeJob::dispatch()->through([new SomeMiddleware]);
Lazy Collections
Lazy collections are a game-changer for working with extensive collections of data, including Eloquent model collections. A new Illuminate\Support\LazyCollection
class leverages PHP’s generators to keep memory low while working with large datasets.
For example, imagine your application needs to process a multi-gigabyte log file while taking advantage of Laravel’s collection methods to parse the logs. Instead of reading the entire file into memory at once, lazy collections may be used to keep only a small part of the file in memory at a given time:
use App\LogEntry; use Illuminate\Support\LazyCollection; LazyCollection::make(function () { $handle = fopen('log.txt', 'r'); while (($line = fgets($handle)) !== false) { yield $line; } }) ->chunk(4) ->map(function ($lines) { return LogEntry::fromLines($lines); }) ->each(function (LogEntry $logEntry) { // Process the log entry... });
Or, imagine you need to iterate through 10,000 Eloquent models. When using traditional Laravel collections, all 10,000 Eloquent models must be loaded into memory at the same time:
$users = App\User::all()->filter(function ($user) { return $user->id > 500; });
However, beginning in Laravel 6.0, the query builder’s cursor
method has been updated to return a LazyCollection
instance. This allows you to still only run a single query against the database but also only keep one Eloquent model loaded in memory at a time. In this example, the filter
callback is not executed until we actually iterate over each user individually, allowing for a drastic reduction in memory usage:
$users = App\User::cursor()->filter(function ($user) { return $user->id > 500; }); foreach ($users as $user) { echo $user->id; }
Eloquent Subquery Enhancements
Laravel 6.0 introduces several new enhancements and improvements to database subquery support. For example, let’s imagine that we have a table of flight destinations
and a table of flights
to destinations. The flights
table contains an arrived_at
column which indicates when the flight arrived at the destination.
Using the new subquery select functionality in Laravel 6.0, we can select all of the destinations
and the name of the flight that most recently arrived at that destination using a single query:
return Destination::addSelect(['last_flight' => Flight::select('name') ->whereColumn('destination_id', 'destinations.id') ->orderBy('arrived_at', 'desc') ->limit(1) ])->get();
In addition, we can use new subquery features added to the query builder’s orderBy
function to sort all destinations based on when the last flight arrived at that destination. Again, this may be done while executing a single query against the database:
return Destination::orderByDesc( Flight::select('arrived_at') ->whereColumn('destination_id', 'destinations.id') ->orderBy('arrived_at', 'desc') ->limit(1) )->get();
Laravel UI
The frontend scaffolding typically provided with previous releases of Laravel has been extracted into a laravel/ui
Composer package. This allows the first-party UI scaffolding to be developed and versioned separately from the primary framework. As a result of this change, no Bootstrap or Vue code is present in default framework scaffolding, and the make:auth
command has been extracted from the framework as well.
In order to restore the traditional Vue / Bootstrap scaffolding present in previous releases of Laravel, you may install the laravel/ui
package and use the ui
Artisan command to install the frontend scaffolding:
composer require laravel/ui php artisan ui vue --auth
For more Information and to build a website using Laravel, Hire Laravel Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop the custom website using Laravel, please visit our technology page
Content Source:
- medium.com
Laravel 5.8.12 released with duplicates collection and other new features
The Laravel team released the 400th release of Laravel (v5.8.12) recently with a new duplicates() collection method and other new features, fixes, and changes to the framework.
First, a new duplicates() method was added to the Illuminate\Support\Collection class:
collect([1,2,1,1,1])->duplicates(); => Illuminate\Support\Collection {#2938 all: [ 2 => 1, 3 => 1, 4 => 1, ], }
It works by returning the indexes of the duplicate values from the original collection object:
$item[0] = 1 is not a duplicate $item[1] = 2 is not a duplicate $item[2] = 1 is a duplicate $item[3] = 1 is a duplicate $item[4] = 1 is a duplicate
Similarly, a new duplicates() method was added to the Eloquent collection class, using the $model->is($another) to check for duplicates. Here’s an example from PR #28194:
use App\User; $one = User::find(1); $two = User::find(1); $three = User::find(1); $users = (new User)->newCollection([$one, $two, $three]); => Illuminate\Database\Eloquent\Collection {#2936 all: [ 1 => App\User {#2929 id: "1", name: "Admin", email: "admin@example.com", email_verified_at: null, created_at: "2019-04-16 23:33:30", updated_at: "2019-04-16 23:33:30", }, 2 => App\User {#2927 id: "1", name: "Admin", email: "admin@example.com", email_verified_at: null, created_at: "2019-04-16 23:33:30", updated_at: "2019-04-16 23:33:30", }, ], }
Next, a new getViews() method was added to the FileViewFinder class, which allows you to retrieve all the view information from currently loaded views. Nothing is new here except the ability to access the $views property via the getViews() method.
As of Laravel 5.8.11, the exit code is captured in scheduled command events, which lead to a new PR providing some helpers available to the scheduler:
$schedule->command('my:command') ->onSuccess(function () { // do something when scheduled command ran successfully }) ->onFailure(function () { // do something when scheduled command failed }) ->pingOnSuccess('https://example.com') ->pingOnFailure('https://example.com') ->emailOnFailure('johndoe@example.com') ;
The emailOnFailure() method is useful when you only want to receive an email for failed scheduled commands as opposed to the emailOutputTo method which is sent no matter what the outcome of the scheduled task. The new scheduler methods have already been added to the scheduling documentation.
Next, the SET datatype was added to the MySQL grammar (learn more about The SET Type):
Schema::create('table_name', function (Blueprint $table) { $table->bigIncrements('id'); $table->set("field_name", [ "Possible", "Values" ]); $table->timestamps(); });
The last new feature in this release is the addition of the in and not in operators, which can be passed as strings to the query builder:
// these two calls produce the same query $query->where('foo', 'in', [1, 2]); $query->whereIn('foo', [1, 2]); // these two calls produce the same query $query->where('foo', 'not in', [1, 2]); $query->whereNotIn('foo', [1, 2]);
You can see the full list of fixes below, and the whole diff between 5.8.11 and 5.8.12 on GitHub. The full release notes for Laravel 5.8 are available in the GitHub 5.8 changelog:
v5.8.12
Added
- Added Illuminate\Support\Collection::duplicates()
- Added Illuminate\Database\Eloquent\Collection::duplicates()
- Added Illuminate\View\FileViewFinder::getViews()
- Added helper methods onSuccess() \ onFailure() \ pingOnSuccess() \ pingOnFailure() \ emailOnFailure() to Illuminate\Console\Scheduling\Event
- Added SET datatype on MySQL Grammar
- Added possibility for use in / not in operators in the query builder
Fixed
- Fixed memory leak in JOIN queries
- Fixed circular dependency in Support\Testing\Fakes\QueueFake for undefined methods
- Fixed exception in lt \ lte \ gt \ gte validations with different types
- Fixed string quoting for SQL Server
- Fixed whereDay and whereMonth when passing int values
Changed
- Added autocomplete attributes to the html stubs
- Improved event:list command
- Updated Illuminate\Database\Console\Factories\FactoryMakeCommand to generate more IDE friendly code
- Added missing LockProvider interface on DynamoDbStore
- Change session’s user_id to unsigned big integer in the stub
For more Information and to build a website using Laravel, Hire Laravel Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop the custom website using Laravel, please visit our technology page
Content Source:
- laravel-news.com
What are the New Features in Laravel 5.5?
Version 5.5 of Laravel is officially released! This release is jam-packed with goodies and improvements, here’s a quick summarizing the highlight features.
1. New Route Methods introduced in Laravel 5.5
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. If you missed them in the release notes, let’s look at them briefly, they are sure to simplify your code and remove a couple of files.
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('/old-about', '/about');
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('/old-about', '/about', 307);
You can coordinate with hired a Laravel developer regarding develop and manage your website with latest laravel tools.
2. Laravel 5.5 Includes TrustedProxy
On a high level, Trusted Proxy tells Laravel about proxies that can be trusted and how to map X-Forwarded-* headers from the request.
Working with Proxies
It’s commonplace for us to need to work with cloud providers like Amazon Web Services and Content Delivery Networks (CDN) like Cloudflare for full site delivery, with the application sitting behind these services instead of being exposed directly to the world. Also, your application might even be behind a chain of proxies.
When your website or application has DNS pointed at CloudFlare, for example, the HTTP requests get proxied from CloudFlare to your application.
3. Dynamic templates in Laravel Blade with View::first
When building dynamic components or pages sometimes we want to display a custom template if it exists or otherwise fall back on a default one.
For example, imagine we are building a pages module, and some pages like “About Us” or “Contact Us” will need a custom template (for example to display pictures or a contact form), while others like “Terms of services” will do fine with a default template.
Using View::first
The view()->first() method allows us to replace the following code:
if (view()->exists('custom-template')) { return view('custom-template', $data); }
return view(‘default-template’, $data);
With a simpler, more expressive version:
return view()->first( ['custom-template', 'default-template'], $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.
Hire Laravel Developer from us, as we give you high quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop the custom web app using Node.js, please visit our technology page.
Content Source:
- laravel-news.com