10 Laravel tricks you need to know

Laravel is the most used web development PHP framework. Around 560K websites are developed with Laravel all around the world. It was created in 2011 by Taylor Otwell and the best thing is that it’s free and open-source.
The framework uses MVC (Model View Control) pattern and it is based on Symfony. It is so widely used because it has so many things from out of the box which makes it very easy to start developing and makes the development process very fast.
Let’s see some tricks in Laravel
1. Default values of Eloquent attributes
One of the things you use all the time are the Eloquents. Since their are connected to the database and we use them to perform CRUD operations you might need to create populate some attributes with default values. Here is how you do it:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
'delayed' => false,
];
}
2. Chunking Results
When you are dealing with thousands of data you need to think about the performance. Laravel eloquents have some special method that allows you to chunk the results and save more memory. The chunk method uses a Closure for processing the data.
Job::chunk(200, function ($jobs) {
foreach ($jobs as $job) {
//
}
});
3. Cursor for database records
Another great way to save up memory when dealing with a lot of data is using the cursor method. The cursor method iterates throw your database records by using a single query but by reducing the memory usage a lot.
foreach (Job::where('is_developer', 'yes')->cursor() as $job) {
//
}
4. Soft deleting
Soft deleting is a nice feature of the eloquent. This feature adds a new column in the database called deleted_at and when use delete on eloquent it doesn’t actually delete the row from the database it just sets deleted_at to the current time. To enable the soft delete you need to add the SoftDelete trait in your Eloquent.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Job extends Model
{
use SoftDeletes;
}
And add the migrations:
public function up()
{
Schema::table('jobs', function (Blueprint $table) {
$table->softDeletes();
});
}
public function down()
{
Schema::table('jobs', function (Blueprint $table) {
$table->dropSoftDeletes();
});
}
You can easily check if the record was softly deleted (trashed) by using a simple method:
if ($job->trashed()) {
//
}
5. Observers and Events in Eloquents
Eloquents have events that are triggered when CRUD methods are called like insert, update, delete, etc. Listening to eloquent events is made very easy by using eloquent observers. It’s a way to decouple the code, basically, a new class where you listen to the eloquent events instead of writing the code in the actual eloquent.
The artisan command to create the observers is:
php artisan make:observer ArticleObserver --model=Article
The observer should look something like this:
<?php
namespace App\Observers;
use App\Models\Article;
class ArticleObserver
{
/**
* Handle the Article "created" event.
*
* @param \App\Models\Article $article
* @return void
*/
public function created(Article $article)
{
//
}
/**
* Handle the Article "updated" event.
*
* @param \App\Models\Article $article
* @return void
*/
public function updated(Article $article)
{
//
}
/**
* Handle the Article "deleted" event.
*
* @param \App\Models\Article $article
* @return void
*/
public function deleted(Article $article)
{
//
}
}
To actually use it is needed to connect the eloquent with the observer in the service provide.
<?php
namespace App\Providers;
use App\Observers\ArticleObserver;
use App\Models\Article;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Article::observe(ArticleObserver::class);
}
}
6. Reduce method
The reduce method iterates throw a collection and returns only one value. It is a easy way to manipulate the collection data.
$collection = collect(["Hello,", "there.", "I am a developer."]);
$text = $collection->reduce(function ($carry, $item) {
return $carry . " " . $item;
});
// result: Hello, there. I am a developer.
7. Laravel jobs
Jobs are very simple classes that allow you to create some code to be executed later on. This is done by using queues. It can be configured by most of the time you use Redis queues.
Lets take example sending emails. Usually it is not necessary to send the email right away. So you usually do a queue to send the emails later one asynchronously so you don’t block the main process since that could be costly in performance. So you create a class for the job that sends the email:
<?php
namespace App\Jobs;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMailable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class EmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $podcast;
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Mail::to('[email protected]')->send(new SendMailable());
}
}
Let’s add submit the job and tell Laravel to execute it after 5 seconds:
$emailJob = (new EmailJob())->delay(Carbon::now()->addSeconds(5));
dispatch($emailJob);
8. Caching
Another feature that you want to know about when dealing with big amount of data is caching. Laravel provides caching types like Redis and Memcacheout of the box. And using those caching storage’s is very easy since there are very easy methods in laravel. Lets take a simple example, lets say we want to cache a query for a certain period of time:
$users = Cache::remember('users', $seconds, function () {
return DB::table('users')->get();
});
9. Query builder
For some operation eloquents may cause performance problems since they are doing a lot of things behind the scene. Or in some cases you don’t want to have a eloquent but you still need to do queries. In cases like this you may want to use the query builder to do CRUD operations.
$employee = DB::table('employee')->where('name', 'John')->first();
10. Aggregates
Both eloquents and the query builder have aggregate functions like, min, max, average etc. Lets take some as a example:
Count:
$employees = DB::table('employee')->count();
Max:
$price = DB::table('orders')->max('price');
Min:
$price = DB::table('orders')->min('price');
Average:
$price = DB::table('orders')->avg('price');
Summary
These features mentioned above are only a few of the many features of the amazing framework. To know more about Laravel features visit their documentation.