Laravel Posts
How to Setup Global Git Ignore in windowLaravel

How to Setup Global Git Ignore in windowLaravel
Lots of developers have a question: How do I create a global gitignore file? so, In this article, I show how to set up a global git ignore.
Reviewing pull requests, I often see contributors sneakily adding editor configuration to the repository’s .gitignore file.
If everyone would commit their environment-specific .gitignore rules, we’d have a long list to maintain! My repository doesn’t care about your editor configuration.
There’s a better solution to this: a personal, global .gitignore file for all your repositories. Here’s how you can set one up. create a .gitignore file for your global rules.
You can also see the following video tutorial as well.
You need to set up your global core.excludesfile configuration file to point to this global ignore file. So, let's start step by step
Step 1:
Create a file .gitignore on your profile C:\Users{username} for example C:\Users\Shailesh
Step 2:
Now you can set a .gitignore path with a three-way. we need to tell this to get this my global git to ignore file.
First Way: Using Windows git bash
Let's open Windows git bash and fire the following command,
git config --global core.excludesFile '~/.gitignore'
Second Way: Using Windows cmd
Let's open Windows cmd and fire the following command,
git config --global core.excludesFile "%USERPROFILE%\.gitignore"
Third Way: Using Windows PowerShell
Let's open Windows PowerShell and fire the following command,
git config --global core.excludesFile "$Env:USERPROFILE\.gitignore"
So, you can easily set the .gitignore global file.
How to develop package into Laravel ?Laravel

How to develop package into Laravel ?Laravel
In our daily life, we are going through lots of packages, and some of us don't know how to build our own package into Laravel.
We are going to perform the core steps to create your own package in laravel. In this tutorial we are going to build a zoom package, so we will perform steps related to it.
Setup Fresh Laravel Repo
Setup fresh laravel repo, and then create directories within it.
for e.g Create infyomlabs/zoom-api directory into the root.
Now create src directory into zoom-api
Run Composer init Into src Directory
After hitting composer init it will ask for some information from you, as you can see below image I have entered some of the information. you can just hit enter if you do not want to add other information.
Add your config file (Optional)
Create a directory config into the src directory and add your config.php file there from where you can manage your env variables.
Add Service Provider
Create your service provider from where you can do lots of actions. like you can publish config/routes/ migrations files from there. Here we are publishing the zoom config file.
Add your class (Which contains all functions)
Here we have added a Zoom class which will contain all zoom functions.
Update Composer.json
Finally, Test it in your existing project
Put the following code to your main composer.json (in your project's root). and hit composer update
"repositories": [
{
"type": "path",
"url": "infyomlabs/zoom-api",
"options": {
"symlink": true
}
}
],
"license": "MIT",
"require": {
"infyomlabs/zoom-api": "dev-develop"
},
Stisla Templates with JQuery DatatablesLaravel

Stisla Templates with JQuery DatatablesLaravel
Today we are going to see how we can generate a data table with one of the most popular a stisla theme.
We can actually do that in minutes with the package that we Recently developed called stisla-templates .
Our team made a great effort into this package and developed it with a new feature. This template package has Jquery Datatable support. So, anyone can easily generate CRUD(scaffold) with a Data table.
Let's see step by step, how we can do that.
You can watch the following video tutorial or follow the article.
Install Packages
Follow the installation steps given in our official documentation of Laravel InfyOm generator and stisla-templates if not installed.
Now, you have to perform the following steps.
composer require yajra/laravel-datatables-oracle:"~9.0"
This package handles the query and frontend stuff.
Register provider and facade on your config/app.php
file.
Now clear your cache and regenerate it using the following command,
php artisan config:cache
We are done with installation and configuration.
Use Generate Scaffold with Datatable
Now I am going to add an option jqueryDT
, at last, to use JQuery Datatables while generating scaffolds. the command looks like
php artisan infyom:scaffold Post --jqueryDT
Enter all required inputs and generate a scaffold of Post.
All views are created inside the posts directory in the resource. Also, the post.js
file is created inside the js directory in assets that are located inside the resource.
Fire the following command for compile and publish the post.js
npm run dev
Now, the data table is ready for use. you can watch the video tutorial here.
How to create custom validation rules in Laravel ?Laravel

How to create custom validation rules in Laravel ?Laravel
While developing complex applications, sometimes we have to validate fields and data in a totally customized way, at that time you can use laravel's custom validations rules functionality.
In this tutorial, we are going to create our own custom validation rule to compare UUID. In our case, I have to check the UUID which is actually a binary string, whether it exists on DB or not.
Laravel doesn't provide any rule to compare that binary UUID string, so we will create our own validation rule.
So let's create our custom validation rule::
Generate Custom Validation Class
So here we have created a new class named UuidExists into App\Rules
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Ramsey\Uuid\Uuid;
class UuidExists implements Rule
{
protected $table;
protected $column;
public function __construct($table, $column)
{
$this->table = $table;
$this->column = $column;
}
public function passes($attribute, $value)
{
$value = Uuid::fromString(strtolower($value))->getBytes();
return \DB::table($this->table)->where($this->column, $value)->exists();
}
public function message()
{
return 'The validation error message.';
}
}
Add Rule to AppServiceProvider
Add your rule to AppServiceProvider.php into boot() method. here I have to give the name uuid_exists to my custom rule. you can give your own name whatever you want.
\Validator::extend('uuid_exists', function ($attribute, $value, $parameters, $validator) {
list($table, $column) = $parameters;
return (new UuidExists($table, $column))->passes($attribute, $value);
});
How to use custom rules?
You can use your custom rule as follows. Here we have using the required and uuid_exists rule, where we are passing attributes and values to our custom rule, which will be used to passes($attribute, $value) function.
'tenant_id' => ['required', 'uuid_exists:tenant_id,uuid']
Keep connected to us for more interesting posts about Laravel.
Send real time notification with Pusher using Laravel and JavascriptLaravel

Send real time notification with Pusher using Laravel and JavascriptLaravel
Here we will learn how to send real-time notifications using Pusher + Laravel.
First of all, you need to create an account in the Pusher and get API keys from there.
Setting up your Laravel application
Now we need to install Pusher SDK, you can install it by the composer using the below command,
composer require pusher/pusher-php-server
After the composer is done, we will need to configure Laravel to use Pusher as its broadcast driver, update the below variables in the .env file,
PUSHER_APP_ID=123456
BROADCAST_DRIVER=pusher
// Get the API Keys from your pusher dashboard
PUSHER_APP_ID=XXXXX
PUSHER_APP_KEY=XXXXXXX
PUSHER_APP_SECRET=XXXXXXX
Open config/app.phpand uncomment the "App\Providers\BroadcastServiceProvider::class".
Now we need an event that will be broadcast to the pusher driver. Let's create a NotificationEvent.
php artisan make:event NotificationEvent
This command will create a below file
namespace App\Events;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class NotificationEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $username;
public $message;
public function __construct($username)
{
$this->username = $username;
$this->message = "{$username} send you a notification";
}
public function broadcastOn()
{
//it is a broadcasting channel you need to add this route in channels.php file
return ['notification-send'];
}
}
Add broadcasting route in channels.php file
Broadcast::channel('notification-send', function ($user) {
return true;
});
Cache Event at Javascript Side
// Initiate the Pusher JS library
var pusher = new Pusher('YOUR_API_KEY', {
encrypted: true
});
// Subscribe to the channel we used in our Laravel Event
var channel = pusher.subscribe('notification-send');
channel.bind('App\\Events\\NotificationEvent', function(data) {
// this is called when the event notification is received...
});
Testing and Setup
Using the below route we can send a notification.
Route::get('test', function () {
event(new App\Events\NotificationEvent('Monika'));
return "Event has been sent!";
});
How to do payments with stripe checkoutLaravel

How to do payments with stripe checkoutLaravel
Payments gateways are very useful components of any e-commerce store. One of the popular payment gateways is Stripe. it's becoming more popular nowadays.
Stripe's simple definition is :
We bring together everything that’s required to build websites and apps that accept payments and send payouts globally. Stripe’s products power payments for online and in-person retailers, subscription businesses, software platforms and marketplaces, and everything in between. ~ Stripe
To begin this laravel tutorial, I hope you already have fresh laravel repo.
Stripe Configuration with Laravel
Run the following command to install stripe :
composer require stripe/stripe-php
if you don't have a Stripe account, you'll want to set that up and add your API keys. Add the following to your .env file.
STRIPE_KEY=your-stripe-key
STRIPE_SECRET=your-stripe-secret
Publish Migrations Files From Stripe
php artisan vendor:publish --tag="cashier-migrations"
And Run migrations by hitting the following command
php artisan migrate
Setup Stripe Controller
Now create a stripe controller by hitting the following command:
php artisan make:controller StripeController
namespace App\Http\Controllers;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Stripe\Checkout\Session;
use Stripe\Exception\ApiErrorException;
/**
* Class FeaturedCompanySubscriptionController
*/
class StripeControlle extends AppBaseController
{
public function createSession(Request $request)
{
setStripeApiKey();
$session = Session::create([
'payment_method_types' => ['card'],
'customer_email' => $userEmail,
'line_items' => [
[
'price_data' => [
'product_data' => [
'name' => 'Make '.$company->user->first_name.' as featured Company',
],
'unit_amount' => 100 * 100,
'currency' => 'USD',
],
'quantity' => 1,
'description' => '',
],
],
'client_reference_id' => '1234',
'mode' => 'payment',
'success_url' => url('payment-success').'?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => url('failed-payment?error=payment_cancelled'),
]);
$result = [
'sessionId' => $session['id'],
];
return $this->sendResponse($result, 'Session created successfully.');
}
public function paymentSuccess(Request $request)
{
$sessionId = $request->get('session_id');
//
}
public function handleFailedPayment()
{
//
}
}
Define Routes
Route::post('stripe-charge', 'StripeController@createSession');
Route::get('payment-success', 'StripeController@paymentSuccess');
Route::get('failed-payment', 'StripeController@handleFailedPayment');
Setup From View file
Here we are going to create stripe session from the backend and redirect to the stripe checkout page once we will receive the sessionId from the backend.
Assume that makePaymentURL is something like "APP_URL/stripe-charge".
Now let's say when you hit the submit form of stripe it will call MakePaymentURL and that URL returns your session ID which we will use to redirect to the stripe checkout page.
$(document).on('click', '#makePayment', function () {
$(this).addClass('disabled');
$.post(makePaymentURL, payloadData).done((result) => {
let sessionId = result.data.sessionId;
stripe.redirectToCheckout({
sessionId: sessionId,
}).then(function (result) {
$(this).html('Make Featured').removeClass('disabled');
manageAjaxErrors(result);
});
}).catch(error => {
$(this).html('Make Featured').removeClass('disabled');
manageAjaxErrors(error);
});
});
That's it, after entering proper details into stripe you will get a success callback to a related route, where you can perform related actions.
How to generate thumbnails by using Spatie Media LibraryLaravel

How to generate thumbnails by using Spatie Media LibraryLaravel
Hope you guys are familiar with Spatie Media Library. It's a very useful and time-saving package to manage file uploading.
It's also providing support to convert your images to thumbnails while storing images. you can generate a thumbnail of the image with the size (height, width) you want.
They are calling thumbnails to Conversions. You can generate multiple thumbnails with different sizes as you want.
So let's see some short examples which help us to create thumbnails of an uploaded image.
Implement the HasMediaTrait into your Model
Here we have a User model and we want to generate a thumbnail of the user uploading his profile image. you have to add HasMediaTrait
to the User model and need to extend HasMedia
.
use IlluminateDatabaseEloquentModel;
use SpatieMediaLibraryModelsMedia;
use SpatieMediaLibraryHasMediaHasMedia;
use SpatieMediaLibraryHasMediaHasMediaTrait;
class User extends Model implements HasMedia
{
use HasMediaTrait;
public function registerMediaConversions(Media $media = null)
{
$this->addMediaConversion('profile-thumb')
->width(150)
->height(150);
}
}
Here we have defined a function registerMediaConversions
in which we can manage the size of a thumbnail, which means how much height or width we want for the thumbnail.
So when we upload an image using the media library,
$media = User::first()->addMedia($pathToImage)->toMediaCollection();
it will auto-generate the thumbnails with the given height and width.
How to fetch the generated thumbnail?
$media->getPath(); // the path to the where the original image is stored
$media->getPath('profile-thumb') // the path to the converted image with dimensions 150*150
$media->getUrl(); // the url to the where the original image is stored
$media->getUrl('profile-thumb') // the url to the converted image with dimensions 150*150
How to generate multiple thumbnails for a single image?
..... in User Model .....
use SpatieImageManipulations;
public function registerMediaConversions(Media $media = null)
{
$this->addMediaConversion('profile-thumb')
->width(150)
->height(150);
}
$this->addMediaConversion('old-profile-thumb')
->sepia()
->border(8, 'black', Manipulations::BORDER_OVERLAY);
}
so, it will generate 2 thumbnails with different image properties. you can use different image properties directly while generating thumbnails.
That's it, you can read more about the spatie media library conversions (thumbnails) here.
Keep connected to us for more interesting posts about laravel.
How to integrate Zoom Meeting APIs with LaravelLaravel

How to integrate Zoom Meeting APIs with LaravelLaravel
Zoom Marketplace is providing APIs to create zoom meetings directly using the web interface and calling its API. So first of all you need to create your zoom ap into zoom marketplace and need to generate the API Keys and credentials.
Create a Zoom Application
- Go to Zoom marketplace and do sign in
- Click the Develop button on the header and select Build App menu.
- Choose the JWT and create an application with the app name that you want.
- Input required information and click Continue until your app will be activated.
I hope you already have installed fresh laravel.Now you have to add the following packages to your composer.json
to integrate the zoom API.
composer require firebase/php-jwt
composer require guzzlehttp/guzzle
And Now run composer update
And don't forget that we also need to modify .env
files to set the zoom API credentials.
ZOOM_API_URL="https://api.zoom.us/v2/"
ZOOM_API_KEY="INPUT_YOUR_ZOOM_API_KEY"
ZOOM_API_SECRET="INPUT_YOUR_ZOOM_API_SECRET"
can find the zoom credentials from your zoom app.
Now just copy the given ZoomMeetingTrait
to your controller and call-related methods.
namespace App\Traits;
use GuzzleHttp\Client;
use Log;
/**
* trait ZoomMeetingTrait
*/
trait ZoomMeetingTrait
{
public $client;
public $jwt;
public $headers;
public function __construct()
{
$this->client = new Client();
$this->jwt = $this->generateZoomToken();
$this->headers = [
'Authorization' => 'Bearer '.$this->jwt,
'Content-Type' => 'application/json',
'Accept' => 'application/json',
];
}
public function generateZoomToken()
{
$key = env('ZOOM_API_KEY', '');
$secret = env('ZOOM_API_SECRET', '');
$payload = [
'iss' => $key,
'exp' => strtotime('+1 minute'),
];
return \Firebase\JWT\JWT::encode($payload, $secret, 'HS256');
}
private function retrieveZoomUrl()
{
return env('ZOOM_API_URL', '');
}
public function toZoomTimeFormat(string $dateTime)
{
try {
$date = new \DateTime($dateTime);
return $date->format('Y-m-d\TH:i:s');
} catch (\Exception $e) {
Log::error('ZoomJWT->toZoomTimeFormat : '.$e->getMessage());
return '';
}
}
public function create($data)
{
$path = 'users/me/meetings';
$url = $this->retrieveZoomUrl();
$body = [
'headers' => $this->headers,
'body' => json_encode([
'topic' => $data['topic'],
'type' => self::MEETING_TYPE_SCHEDULE,
'start_time' => $this->toZoomTimeFormat($data['start_time']),
'duration' => $data['duration'],
'agenda' => (! empty($data['agenda'])) ? $data['agenda'] : null,
'timezone' => 'Asia/Kolkata',
'settings' => [
'host_video' => ($data['host_video'] == "1") ? true : false,
'participant_video' => ($data['participant_video'] == "1") ? true : false,
'waiting_room' => true,
],
]),
];
$response = $this->client->post($url.$path, $body);
return [
'success' => $response->getStatusCode() === 201,
'data' => json_decode($response->getBody(), true),
];
}
public function update($id, $data)
{
$path = 'meetings/'.$id;
$url = $this->retrieveZoomUrl();
$body = [
'headers' => $this->headers,
'body' => json_encode([
'topic' => $data['topic'],
'type' => self::MEETING_TYPE_SCHEDULE,
'start_time' => $this->toZoomTimeFormat($data['start_time']),
'duration' => $data['duration'],
'agenda' => (! empty($data['agenda'])) ? $data['agenda'] : null,
'timezone' => 'Asia/Kolkata',
'settings' => [
'host_video' => ($data['host_video'] == "1") ? true : false,
'participant_video' => ($data['participant_video'] == "1") ? true : false,
'waiting_room' => true,
],
]),
];
$response = $this->client->patch($url.$path, $body);
return [
'success' => $response->getStatusCode() === 204,
'data' => json_decode($response->getBody(), true),
];
}
public function get($id)
{
$path = 'meetings/'.$id;
$url = $this->retrieveZoomUrl();
$this->jwt = $this->generateZoomToken();
$body = [
'headers' => $this->headers,
'body' => json_encode([]),
];
$response = $this->client->get($url.$path, $body);
return [
'success' => $response->getStatusCode() === 204,
'data' => json_decode($response->getBody(), true),
];
}
/**
* @param string $id
*
* @return bool[]
*/
public function delete($id)
{
$path = 'meetings/'.$id;
$url = $this->retrieveZoomUrl();
$body = [
'headers' => $this->headers,
'body' => json_encode([]),
];
$response = $this->client->delete($url.$path, $body);
return [
'success' => $response->getStatusCode() === 204,
];
}
}
And add the following constants to your controller.
const MEETING_TYPE_INSTANT = 1;
const MEETING_TYPE_SCHEDULE = 2;
const MEETING_TYPE_RECURRING = 3;
const MEETING_TYPE_FIXED_RECURRING_FIXED = 8;
So the final controller will look like,
namespace App\Http\Controllers;
use App\Models\ZoomMeeting;
use App\Traits\ZoomMeetingTrait;
use Illuminate\Http\Request;
class MeetingController extends AppBaseController
{
use ZoomMeetingTrait;
const MEETING_TYPE_INSTANT = 1;
const MEETING_TYPE_SCHEDULE = 2;
const MEETING_TYPE_RECURRING = 3;
const MEETING_TYPE_FIXED_RECURRING_FIXED = 8;
public function show($id)
{
$meeting = $this->get($id);
return view('meetings.index', compact('meeting'));
}
public function store(Request $request)
{
$this->create($request->all());
return redirect()->route('meetings.index');
}
public function update($meeting, Request $request)
{
$this->update($meeting->zoom_meeting_id, $request->all());
return redirect()->route('meetings.index');
}
public function destroy(ZoomMeeting $meeting)
{
$this->delete($meeting->id);
return $this->sendSuccess('Meeting deleted successfully.');
}
}
So this is all you need to integrate the zoom API, so easy 😊 Right. Enjoy the code.