Nasrul Hazim Bin Mohamad

Laravel: Display Progress Bar in Seeder

Jun
18

Assalamualaikum / Hi,

Recent projects development require me to have numbers of seeders – this include some dummy data.

Each time seeding new / old data, it’s kinda boring to wait it’s done.

So I just need to know, how much the progress of the seeding. Following is the trait I’ve created to generate the progress bar.

Sample output:

Hope this small snippet benefit anyone in need displaying the progress of the seeding.

Happy coding guys!

Laravel: Import Templates into Laravel

Apr
27

Assalamualaikum,

We know, there’s millions of web templates available out there – the clean look, corporate look, modern, minimalist. You name it, either it is free or paid version, usually it come in HTML, JS and CSS format. It’s hard to find template that is ready with Laravel.

Previously, here are some of the approaches I did, to get the template into Laravel application.

  1. Download the template, copy the assets, organise them in public directory. That’s ok, but I need a way to keep everything in resources/assets.
  2. Download the template, mimic / copy the important part of the template – CSS / JavaScript – place it in resources/assets and start writing codes for front-end assets, then compile using Laravel Mix.
  3. Get the list of dependencies used for the theme, manually install using yarn add..., then create scripts – CSS / JavaScripts – in resources/assets, then compile using Laravel Mix.

All these some of my previous approaches in importing templates into Laravel application.

Yesterday, I have a chance experimenting on new method. Here the workflow:

  1. Clone / Download the template into resources/assets/templates/
  2. In terminal, go into resources/assets/templates/the-template/, run npm install && npm run build – depending on your template selection, sometimes it is required to compile the template, but there is templates that did not require you to compile.
  3. Then in webpack.mix.js, copy all assets generated in resources/assets/templates/the-template/ to public/the-template.

Then you are done! You can start use the asset() helper like asset('the-template/js/vendor.js'), and so on in your layouts.

Following an example of the templates I have compile and export to public folders – but I did not implement in the new layout, as it require a lot of efforts to create components and use all the classes from the template.

Template Into Laravel

Hope my explanation will make you guys clear, how to import templates into Laravel projects – 3 main steps: git clone, build(optional), copy compiled assets with mix to public directory.

Thanks!

Laravel: HasDatatable Trait

Apr
26

Assalamualaikum,

Just a simple setup on datatable – to have a trait that can be use for other models.

Assumed that you already install Yajra Datatable, we going to setup the API end point, simplify the setup of datatable.

Here the trait:

You can use the protected $datatable property to select which fields to display in your datatable.

The usage:

The API Endpoint:

Then you are done!

You may overwrite the datatable scope in your model if you need other implementation for the scope.

This is just one neat simple setup, reusable to your other models.

Hope this can help speed setup your datatable API Endpoint.

Thanks for reading!

p/s: You may see this setup in Cleanique Coders Boilerplate.app.

Laravel: Observer Setup Enhancement

Apr
24

Assalamualaikum,

It’s been awhile since my last blog post. Today, just want to share something simple, an enhancement of LARAVEL: CREATE HASHED ID FOR A RESOURCE USING OBSERVER. Going to refactor a bit.

First, let’s modify the app/Observers/Kernel.php, to be like the following:

Next, add new config file for our observer – config/observers.php:

And that’s it!

Very simple and straightforward setup of Laravel Observer, much cleaner than before.

Should I make this as a package? Do let me know if you guys need this as a package. 🙂

Thanks

Laravel: Create Telegram Bot Application without Botman Studio

Mar
21

Installation

We are using Botman package, and Botman Telegram Driver.

Configure .env

Use Bot Father to create new bot and get the API Token for the bot, store it in .env.

TELEGRAM_TOKEN="your-bot-api-token"

Telegram End Point

Create a route & controller for your Telegram Bot to use after this (webhook).

In TelegramController, add the following:

Now you are done preparing for next part.

Webhook

For development purpose, you can use valet share to have a live server. For Windows / Linux, you can install ngrok.io to have a live server.

valet share is actually running a ngrok.

Run command valet share and and then register our app with Telegram using php artisan botman:telegram:register command.

CSRF Token

In App\Http\MiddlewareVerifyCsrfToken, disable CSRF token for /telegram route.

One you are done setting up the webhook, open up your Telegram, start talk with your bot, /hi. You should received response from your bot.

Laravel: Datatable

Feb
18

Assalamualaikum / Hi,

Today I will share how to use Datatables in your Laravel project.

I will cover on:

  1. Setting up Datatables
  2. Compiling Datatables Asset with Laravel Mix
  3. Create route for Datatables
  4. Create reusable Blade Template for Datatable

Part 1: Installation

Create a new laravel project. Install package.json dependencies with npm install or yarn install. Add Datatable and Datatable Bootstrap 4 – yarn add datatables.net datatables.net-bs4 --dev. --dev means that we only need this on development since we will compile it once and used the compiled version for our application.

Open up webpack.mix.js and update the file as following.

Then run npm run prod – this should create public/js/datatables.js and public/css/datatables.css

The next thing you need to install is the Yajra Laravel Datatablescomposer require yajra/laravel-datatables:^1.0 and then run php artisan vendor:publish --tag=datatables.

If you’re running on minimum of Laravel 5.5, thanks to package discovery. No need to setup config/app.php. 🙂

Part 2: Datatable Routes

In this part, I’m going to show how I manage Datatable routes.

The starting point is the app/Providers/RouteServiceProvider.php. Open up the file and we will duplicate one of the method – mapApiRoutes() – and name it as mapDatatableRoutes().

Next, create routes/datatable.php file and we can start write datatable routes in the file. As you can see, with this method, your datatable routes will be much cleaner and organised in a separate route file.

This is just an approach to make your route file easier to maintain. The other option, you may use macro.

Following are the sample datatable route that we will use in this post.

<?php 

Route::get('user', 'UserController')->name('user');

Part 3: Basic Datatable Controller

In this part, I’ll show how I manage the controllers for datatables. As you can see from my mapDatatableRoutes(), I have namespace for the datatable route to App\Http\Controllers\Datatable. This approach just to make your datable controllers well organise.

You can create your first datatable controller with php artisan make:controller Datatable/UserController and you can copy paste the basic setup of the datatable controller.

Part 4: View

In this part, I’ll show how I create basic datatable blade component that reusable – of course, you can use VueJs as well, but I’ll keep it simple for now.

By default, I have this resources/views/components/table.blade.php, which I always use for table based view.

Next, create resources/views/components/datatable.blade.php.

Now we are prepared with the requirements on datatable – Datatable JS & CSS, Laravel Datatable by Yajra, dedicated route and namespace to keep codes well organised. Next, we will test our setup.

Part 5: Final Countdown

We will list out users using datatable. Make sure to run php artisan make:auth and add @stack('styles') and @stack('scripts') in resources/views/layouts/app.blade.php.

Previously you have setup the route and controller. Next is to create a controller, route and a view to display the data from datatable. Following are the setup.

Create the controller – php artisan make:controller UserController -r

Create resources/views/users/index.blade.php

Add route for the view in routes/web.php: Route::get('/users', 'UserController@index')->name('user');

Next (2 more steps!), seed some data with tinker php artisan tinker, then factory(\App\User::class,100)->create();.

And finally, run php artisan serve, the go the browser – http://127.0.0.1/users, you have as the datatable display nicely!

Conclusion

So, as conclusion, the tedious part is to setup the requirement for the datatable. Once you’re done, you will probably will involved with creating route, controller for the datatable and view, and view for the controller view.

You can extend the datatable blade component based on your needs. As for me, for now, the basic setup is good enough.

Here the repository for this post example.

Should I create a package for this?

Thanks! Happy Coding!

Laravel: Notification to Slack

Feb
02

Assalamualaikum / Hi,

Today I will show you how to make a notification to Slack channel.

The approach slightly different you may came across on the internet, but they key point, still rely on Laravel Notification. It’s just how I manage my Slack service.

Configuration

First, we going to start with setting up our environment for Slack Notification by adding the Slack service configuration. Add new services in config/services.php:

Then create a webhook URL in Incoming Webhooks.

In your .env, add SLACK_WEBHOOK_URL, and add the webhook you just created above.

Once you’re done, in your terminal, don’t forget to run php artisan config:cache.

Service

Next step is to setup our Slack service and helper.

The service basically it’s just a simple class to have a webhook URL store in it, and a helper make it simpler to call the Slack service.

We going to create a service class in app/Services/Slack.php:

Then create a helper in app/Support, call it helpers.php. Then add the following and then make sure in composer.json, to load the app/Support/helpers.php:

Then composer dumpautoload -o once you have added the helper.

Notifiable Trait

Laravel provide a trait Illuminate\Notifications\Notifiable, which you can use it anywhere in any classes you want.

In our case, I want to create a class called Notify.php in app/Models.

Did you notice how I use slack() helper to get the Slack Webhook URL? Much convenient. You may want to extend the Slack service class in future, but in our case, we don’t need any as for now.

But again, you can simplify that by using env() function to get the Slack Webhook URL instead of having configuration, helper and Slack service class.

This is just my practice when dealing with 3rd party service – configuration, service class and a helper.

Don’t forget to composer dumpautoload -o once created the class.

Do take note the routeNotificationForSlack(), that is required in order Slack to work. Next will see how to notify to Slack channel.

Notification

This it the last section – now go and create a notification class via artisan – php artisan make:notification NotifyToSlackChannel.

Open up the NotifyToSlackChannel class and do two things:

One, update the via() method to accept only slack in the array.

Two, add a new method called toSlack($notification) and use \Illuminate\Notifications\Messages\SlackMessage to send messages to Slack channel.

Both steps above in following gist:

Let’s try!

So, you are ready to send messages to your Slack channel!

The fastest way to test your Slack notification is using tinker.

Here how I did:

Save it to tinker/notify-to-slack.php.

Then run php artisan tinker tinker/notify-to-slack.php.

That’s it! Working great!

User Cases

Some of user cases might need this type of notification:

  1. Helpdesk system – quick response from support team when get notify on new issues raised.
  2. E-commerce – placing new order, successful payment, out of stock items.
  3. Attendance system – you want know what time your employee come to your office (of course involve some other integration)

And I believe, it’s quite a lot of user cases can be implement, especially those involved with support, request, management.

Feel free to share your idea how we can implement more with Laravel Notification and Slack. 🙂

Happy coding guys!

Laravel: Packager

Jan
28

Assalamualaikum / Hi,

In this post, I will talk more about Laravel Package Generator, Packager.

And today, this morning, I just created Money Wrapper, a Money wrapper, and of course using Packager.

Before we go to the things inside Packager, here the package Money Wrapper provide:

  • Provide a Money helper – money()
  • Intended for Laravel Framework, but can be use outside from Laravel Framework as well.
  • Provide common usage such as:
    1. For Human Readability – RM 1.00, RM 345.00
    2. For Common Display – 1.00, 345.00
    3. For Machine (intended format to store in Database – integer) – 100, 34500
    4. Fixed Exchange Rate Conversion – $ 1 > RM 3.87

So, that’s just briefly about the package, you may go ahead to Money Wrapper to start use it.

Package Skeleton

First thing first, I’ve already give a short update about Packager, a Laravel Package Generator – help to speed up setup Laravel package skeleton.

The command to create new package is simple:

$ packager skeleton "Cleanique Coders" "Demo Package"

Following are the sample package generated:

Package Skeleton Generated

And other than generate the skeleton for you, it’s also install all the dependencies and initialise git! Fuh! Save lot time!!

The Skeleton Details

Files and Directories

As you can see, composer(including lock), LICENSE.txt, phpunit.xml, README.md files included in the package.

Then the structure of having src, tests and vendor already in place.

Source

Taking a bit deeper into src directory, we have the Facade and Service Provider. This is by default generated by the package. Come along in the directory is Support directory, which usually in the directory we have a helper file – which already auto loaded during package initialisation! Very helpful!

Test

Next, as for tests, the tests directory already setup and have a default TestCase.php, which our main file. This TestCase.php, we should extend from it when creating new test(make sure to have the suffix Test.php of the file name – you may change in phpunit.xml if you wanted to). TestCase.php also already load up your package service provider – so you don’t need to worry setting up migration. I would probably add some other setup like database settings to use SQLite in future.

I’ve also added Code Dungeon, PHPUnit Result Printer and Orchestra TestBench which both would be helpful in your test development for Laravel package.

Conclusion

As the conclusion, you might experienced (if you already have previously write packages), where you have missed out one or two things, or even, kinda difficult to setup one by one for your Laravel package – this is absolutely a solution for you!

For me, I’m bit lazy, and kinda irritate to keep on repeating setup the same thing, so I’ve decided to create the Packager!

And for me again, if i’m not satisfied with what’s exist, I’ll build it myself (of course with Allah’s will, insyaAllah).

When there’s a will and efforts, there’s always a result.

Hope this Packager, will help more people to learn not just about creating Laravel package, also, build a good structure and standard across Laravel packages. I did study how Laravel packages available setup, including those from Spatie, and many more. So this is the result.

Hint: Will add up for updates on Packager. Stay tuned!

Laravel: Activation Account by E-mail – Part 2

Jan
13

Continue from previous post, next we going to setup the middleware in order to check either the user already activate the account or not.

If user already activate the account, allow to enter our application, else redirect to request for another activation e-mail.

Laravel: Create Welcome Email

Jan
13

A quick post on how to setup a welcome email on user registration.

Make sure you have a mailtrap.io account for testing purpose, or production you may use SparkPost, or GMail SMTP, or any provider should work with proper .env on mail configuration.