fabiochiu/medium-articles huggingface dataset:
Breaking
By: J.D. Harms
Tags: Poem, Madness, Dissolution, Image, Poetry

Breaking

Photo by Jr Korpa on Unsplash

Now this new disruption

begins eating at the heart

full of prophetic vitamins

cigarette smoke that clears

the sinuses

then the smarting of the tissue

that collides with glass

the mirror tired of Narcissian

antics

the full ignorance of Echo

as a character, as a love

the rum bottles have organized

the next protest march

unused recycling bins

providing the security

while the hairdressers

abandon the politicians en masse

everyone drooping with heavy

heads

and the silent trees

their winter nudity notwithstanding

look on with nothing to add
Compulsion
By: J.D. Harms
Tags: Relationships, Love, Image, Poetry, Desire

Compulsion

Photo by Jr Korpa on Unsplash

It’s so easy for me to get lost in the pull of your arms the gravity towards a new nudity a sentence for how we can be lovers and that I keep coming back here I keep coming back here ignoring road signs and other signals to the contrary even having failed the trial by water I’d give over to the bed for the whole season I cannot see the district’s notifications I don’t know where to go out from here but I give up on the dentist on the whores on the dead raccoon on the highway falcons lighting up the power lines squeezing whole fruits inside my mouth drip down lips finding hands a discursive reticence filled by tongue but lashed backwards immediately forced to the taste of the smell of the touch that draws on and onwards and escapes from nothing just to feel you again.
Laravel 8 : Membuat RESTful API CRUD Sederhana
By: Aji Gojali
Tags: Postman, API, Restful, Crud, Laravel

Membuat Controller — Untuk membuat controllernya kalian bisa ikuti sctrip di bawah ini.

php artisan make:controller CompanyController --force --api --model=Company

Membuat controller

Untuk penjelasannya di bawah ini.

-- force = membuat class/file dengan menimpa atau mengganti jika class yang sudah ada

--api = membuat controller untuk API tanpa dengan membuat method create dan edit

--model = membuat controller dengan mengarahkan pada model tersebut

Di dalam controller sudah terbuat method-method-nya seperti index, store, show, update, destroy. sekarang kita tinggal isi script sesuai kebutuhan kita.

Method index — Method ini digunakan untuk menampilkan data yang berbentuk list. contohnya seperti dibawah ini.

use Illuminate\Http\Response; ... /**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/ public function index()

{

return response()->json(Company::paginate(10), Response::HTTP_OK);

}

Method store — Method ini digunakan untuk menyimpan data. dan ini contoh codenya.

/**

* Store a newly created resource in storage.

*

* @param \Illuminate\Http\Request $request

* @return \Illuminate\Http\Response

*/ public function store(Request $request)

{

// Validation

$rules=[

'name' => 'required',

'email' => 'nullable|email'

];



$validator = Validator::make($request->all(), $rules);



if($validator->fails()){

return response()->json(['message'=>$validator->errors()], Response::HTTP_BAD_REQUEST);

}



Company::create($request->all());

return response()->json(null, Response::HTTP_CREATED);

}

Method show — Method ini digunakan untuk menampilkan data dalam bentuk satu data. contoh codenya.

/**

* Display the specified resource.

*

* @param \App\Models\Company $company

* @return \Illuminate\Http\Response

*/ public function show(Company $company)

{

return response()->json($company, Response::HTTP_OK);

}

Method update — Method ini digunakan untuk mengupdate data. bisa kalian ikuti codenya di bawah ini.

/**

* Update the specified resource in storage.

*

* @param \Illuminate\Http\Request $request

* @param \App\Models\Company $company

* @return \Illuminate\Http\Response

*/ public function update(Request $request, Company $company)

{

// Validation

$rules=[

'name' => 'required',

'email' => 'nullable|email'

];



$validator = Validator::make($request->all(), $rules);



if($validator->fails()){

return response()->json(['message'=>$validator->errors()], Response::HTTP_BAD_REQUEST);

} $company->update($request->all());

return response()->json(null, Response::HTTP_NO_CONTENT);

}

Method destroy — Method ini digunakan untuk menghapus salah satu data. dan ini contoh codenya.

/**

* Remove the specified resource from storage.

*

* @param \App\Models\Company $company

* @return \Illuminate\Http\Response

*/ public function destroy(Company $company)

{

$company->delete();

return response()->json(null, Response::HTTP_NO_CONTENT);

}

Setelah selesai membuat controller kita akan membuat routes.
Part 1: Building a CRUD system using Laravel 8, Laravel Orion, Angular 11 & JWT
By: Shreejan Shrestha
Tags: Jwt, Laravel Orion, Rest Api, Angular, Laravel

In this series we’re going to be building a complete CRUD application using Laravel for REST API and Angular on the frontend. In this part, we’ll setup the API part using Laravel Orion. Laravel Orion is a new library which helps us to simplify the API development for our application.

We will start with a fresh installation of Laravel. On this tutorial we will be using composer to create a new Laravel project. However, you can use any other ways to create your project as described in the Laravel docs.

Let’s create a new Laravel project named “crud-app” using the following terminal command:

composer create-project laravel/laravel crud-app

This will create a new Laravel project in the directory you execute the command from. Now, we’ll need to switch to our app directory and start our application using:

cd crud-app php artisan serve

If everything works well, you Laravel app should now be up and running at: http://127.0.0.1:8000/. This will be our base url which we are going to use later for our API.

Next, let’s install the Laravel Orion package, which, we will be using to build our APIs.

composer require tailflow/laravel-orion

Now, we’re ready to start with our API development. We’ll be creating a simple CRUD for managing articles, which will have a title and content. For this you will need to connect our application to the database. So, we’ll be updating our database details on the .env file of our Laravel project. For this tutorial I’m using a MySQL database with the following details. You will need to configure the database configurations according to your database installation.

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=crud_app

DB_USERNAME=root

DB_PASSWORD=admin

After we’ve setup our database configurations, we’re ready to create our articles table. For this we’re going to generate a database migration using:

php artisan make:migration create_articles_table

This should generate a new class named CreateArticlesTable at the database/migrations folder. We’ll now add these two lines on the up() method of this class.

$table->string('title');

$table->string('content');

So, our complete class would look like this:

Now, lets run our migration using the following command:

php artisan migrate

This command will create the articles table on our database along with other tables like users, password_resets etc which are shipped with Laravel by default.
Install Laravel Installer in Mac OS
By: Shamshad Zaheer
Tags: Laravel Installation, Installer, Laravel

Install Laravel Installer in Mac OS

In order to install Laravel Installer in your Mac OS. Open your terminal and type the following command.

composer require global “laravel/installer”

Once the laravel installer is installed, in order to use it through out the terminal we need to the add the path to our bash profile file.

To do so type the following command in order to open bash profile file.

nano .bash_profile

Once the bash profile get open. Type the following to store the path

export PATH=”$PATH:$HOME/.composer/vendor/bin”

Now to save and close the file. CTR + X and type yes

Now restart the terminal or just type the following command

source .bash_profile
從零到有建立 Laravel 測試
By: Andy Chou
Tags: Unit Testing, Mockery, Feature Testing, Laravel, Ci Pipeline

針對 model 做單元測試

測試 model 中的 relationship 是否正確。 測試的 function 名稱不用駝峰式命名法是因為想把測試的完整內容記錄下來, 看code的人才可以一目瞭然知道這在測什麼。 RefreshDatabase 這個 trait 會在跑每個測試 function 時執行 migrate:fresh 重置資料庫。 這邊有個小坑，若你是用指令 php artisan make:test UserTest — unit 產生 testcase 的話，會遇到 unit test 中抓不到 factory 的 bug，目前官方文件是解釋說 unit test 本來就不應該用 factory 產生假資料。這邊我是參考此篇文章將 use PHPUnit\Framework\TestCase; 改為 use Tests\TestCase; 。

tests/Unit/GoogleReviewJobTest

1. 測試 google_review_job 是否包含許多 google_reviews。

class GoogleReviewJobTest extends TestCase

{

use RefreshDatabase;



public function test_google_review_job_has_many_google_reviews()

{

// Arrange(create 1 google_review_job & 3 google_reviews)

factory(GoogleReviewJob::class)->create();



// Act

$googleReviewJob = GoogleReviewJob::first();

$googleReviews = GoogleReview::all();



// Assert

// Method 1: Count that a googleReviewJob googleReviews collection exists.

$this->assertEquals(3, $googleReviewJob->reviews->count());

// Method 2: googleReviews are related to googleReviewJob and is a collection instance.

$this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $googleReviewJob->reviews);

}

}

tests/Unit/GoogleReviewTest

1. 測試 google_reviews 是否屬於 google_review_job。
Validate Video Duration in Laravel
By: Rajesh Chaurasiya
Tags: Laravel Development, Laravel Framework, Videos, Laravel, Laravel8

So.. Many times you have found yourself stuck in the situation where you how medium pays for writing articleshave to validate the video length of file when the user uploads the video. Unfortunately Laravel doesn’t provide any way to validate video length. So in this post i am going to show you a very easy method to validate video length. It is independent of the video mime type.

I assume you have some basic knowledge of laravel otherwise why you would be here… Just kidding…

This is my front-end for laravel basic form it.

now my web.php file

before i copy-paste further code. i would like to highlight that we are gonna use a composer package.

composer require pbmedia/laravel-ffmpeg

so now have a look at my VideoValidationController.php

you might here notice that i am using array notation for specifying rules for my video validation. Because this notation gives us freedom to use our own validation rules….. Now you might have guessed till now that i am gonna make custom rule for this… It is pretty easy.

php artisan make:rule VideoDurationValidation

here is my code.

so let me tell you some of the points about this validation rule. … It just takes two parameters. 1st is lower limits for video length (in minutes) and 2nd is upper limit for video length(also in minutes). The second parameter is optional. this is set to PHP_INT_MAX. so you can choose any length.

Hope it helps… feel free to message me in the comment box.
Laravel with Firebase Cloud Messaging FCM Notification Part 2 “store users notification on the…
By: Ibrahim Madi
Tags: Notifications, Firebase Cloud Functions, Supervisor, Laravel, Laravel 7

Laravel with Firebase Cloud Messaging FCM Notification Part 2 “store users notification on the database and fetch it with queue and supervisor” Ibrahim Madi Dec 25, 2020·2 min read

#Note parte 1 https://medium.com/@ibrahim.s.m.2010/laravel-with-firebase-cloud-messaging-fcm-part-1-64de03134c00

Step1: Create a migration for the notifications table



php artisan notifications:table

Step2: Migrate the notifications table

php artisan migrate

Step3: Create a new notification class

php artisan make:notifiaction PushNotification

Step4: Update PostObserver to send a notification with class PushNotification

Step5: Setup Notification Events

When a notification is sent, the Illuminate\Notifications\Events\NotificationSent event is fired by the notification system. This contains the "notifiable" entity and the notification instance itself. You may register listeners for this event in your EventServiceProvider :

protected $listen = [

'Illuminate\Notifications\Events\NotificationSent' => [

'App\Listeners\LogNotification',

],

];

Step6: Create LogNotification and handle send notification

Step7: add icon notification and badge count in ‘layouts.app’ navbar

Step8: Setup View Composers to share notifications

Add it in the app.php/providers list

App\Providers\ViewServiceProvider::class,

Step9: now $notification and $notificationCount share with ‘layouts.app’

Step10: now it’s ready to push notifications

#Note change from env QUEUE_CONNECTION=database

# install supervisor

sudo apt-get install supervisor Supervisor configuration files are typically stored in the /etc/supervisor/conf.d directory. Within this directory, you may create any number of configuration files that instruct supervisor how your processes should be monitored. For example, let's create a laravel-worker.conf file that starts and monitors a queue:work process: [program:laravel-worker]

process_name=%(program_name)s_%(process_num)02d

command=php /home/forge/app.com/artisan queue:work sqs --sleep=3 --tries=3

autostart=true

autorestart=true

user=forge

numprocs=8

redirect_stderr=true

stdout_logfile=/home/forge/app.com/worker.log

stopwaitsecs=3600



for example it local fcmapp

command=php /var/www/html/fcmapp/artisan queue:work sqs --sleep=3 --tries=3 stdout_logfile=/var/www/html/fcmapp/worker.log

Thanks for your time :) .
Laravel File Permission in Ubuntu Server
By: Hafiq Iqmal
Tags: Ubuntu, Servers, Laravel

I found that there is a lot of developer have issues which files/folders permission when setup a project in staging/production server.

Here is where i solved every time i faced permission issues.

After composer install ,

Most important, need to make sure the storage folder and bootstrap/cache is in proper permission. The application directory is owned by our system user and is readable but not writable by the web server. It’s correct but there are few directories that need special treatment. Let’s change the group ownership of the storage and bootstrap/cache directories to www-data.

# sudo chgrp -R www-data storage bootstrap/cache

# sudo chmod -R ug+rwx storage bootstrap/cache

2. Make sure all the files in 664 or 644 and 775 or 755 for folders. In my case :-

# sudo find project_folder -type f -exec chmod 664 {} \;

# sudo find project_folder -type d -exec chmod 775 {} \;

I see a lot of developer recommend other developer to use 777 🤷‍♂️. Don’t they know 777 is dangerous move. Refer here.

3. There is a case that your application can’t write/read your logs file. But first, delete everything inside logs folder

# sudo chmod g+s storage/logs/

# sudo setfacl -d -m g::rwx storage/logs/

This will inherit the permission from the parent folder

This helps me every time. Hope its help 😁
Laravel Eloquent Filteration using Pipeline
By: Hafiq Iqmal
Tags: Middleware, Laravel, MySQL, Pipeline, Eloquent

One of the features of Laravel which surely useful is the pipeline. Pipelines is one of the most used components in the Laravel for example middleware.

Basically, with a pipeline we can pass an object through a stack of tasks and get the result via a callback.

The benefit of pipeline for query filtering is that we can reduce tons of lines to several lines. Being unaware of the pipelines, we would usually set up a controller, get an instance of Eloquent of User model, and apply some condition based on query string.
How to Configure Mailgun in LaraContact to Send Emails
By: Emmanuel Eliason-Armstrong
Tags: Contact Management, Mailgun, Laracontact, Laravel, Contact Manager

LaraContact is an absolute multi user’s online contact management application that helps you organize your contacts in a centralized location.

Online contact management application built with Laravel

In this article, you will learn about the procedure to configure Mailgun in LaraContact to send emails, so follow the steps written below for quick and easy integration.

What is Mailgun?

Mailgun is the all-in-one, intelligent email delivery platform trusted by businesses, loved by developers.

One of the huge benefits of Mailgun is that they allow you to send up to 10,000 emails/month for free in their free plan. If you exceed the limit of the free plan in a month, then every 1000 emails cost 0.50$. The limit of 10,000 emails is more than you might need if you are a small business or an individual. Read more about the Mailgun plans.

How to Configure Mailgun in LaraContact

Configuring Mailgun in LaraContact only takes a few minutes. It’s definitely one of the easiest transactional email services out there to setup. Follow the steps below:

Step 1 : Signup for a free account

First, signup for a free account at Mailgun.com And then Log in to your Mailgun account with your login credentials.

Step 2: Grab your Mailgun API Key

When you sign up for Mailgun, they generate a primary account API key.

This key allows you to perform all CRUD operations via various mailgun API endpoints and for any of your sending domains. To view your API key:

Click on Settings on the left-hand side of the Mailgun dashboard.

Select API Keys from the menu below on the left-hand side.

On the following page, under the API Keys section, you’ll see your Private API key.

Click on the eye icon to make the full API key visible.

mailgun apikey

Step 3: Configure LaraContact to send emails

Log in to LaraContact portal using your admin credentials and choose Site Configuration From the caret ‎Dropdown menu.

Enter your mailgun domain and API Key from Step 2 and click on “Save Settings” to apply the changes.

Then click on “Send Email” and send a test email to ensure everything is working correctly.

send an email with LaraContact

Voila!! All emails from your LaraContact application will now go out via Mailgun’s mail servers.
Why use fillable in Laravel
By: Mohd Daud Khan
Tags: Laravel

Fillable is a protected property of a Model class and with the help of fillable property we can use short way to insert data into database like

User::create($request->all());

Or

$arrayOfData = ['name' => 'Doe', 'email' => 'test@test.com', ...];

User::create($arrayOfData);

Or

$user = new User;

$user->fill($arrayOfData);

Without fillable we need to write more code like

$user = new User;

$user->name = $request->input('name');

$user->email = $request->input('email');

...

...

$user->save();

Remember: Mass assignment vulnerability can occurs when we use fillable. To avoid use proper validation.
[Laravel] There is no role named `xxx` laravel
Tags: Laravel Permission, Laravel

當使用 laravel-permission 時，使用

$user->assignRole(`xxx`);

跳出錯誤 There is no role named `xxx`

只要在model中加入

protected $guard_name = ‘xxx’;

搞定
How to Install Laravel 8 on Server?
By: Shahzeb Ahmed
Tags: Cloudways, Cloudways Hosting, Laravel Installation, Laravel, Laravel8

Laravel 8 was made available on September 8, 2020. Laravel 8 continues the improvements made in Laravel 7.x including a Laravel Jetstream, migration squashing, job batching, improved rate-limiting, dynamic Blade components, Tailwind pagination views, time testing helpers, event listener improvements, improvements to artisan serve, and a variety of other bug fixed and usability improvements.

Server Requirements:

Laravel 8 requires the following configuration to install laravel 8 on the server. And Cloudways is one of the Managed Hosting providers which support all these below requirements.

PHP Version 7.3

Fileinfo PHP extension

JSON PHP Extension

Mbstring PHP Extension

OpenSSL PHP Extension

BCMath PHP Extension

Tokenizer PHP Extension

XML PHP Extension

Ctype PHP Extension

PDO PHP Extension

Install Laravel 8 on Cloudways Platform:

I’m assuming that you already signed up for a Cloudways account.

To Install Laravel 8 on the server, select your server and application according to your project requirements. Select server size as per your website traffic, and location according to your preferred region.

After clicking Launch Now. it takes 3–5 minutes and your PHP application will install to the Server. Click on it to find further details inside:

Now, to install Laravel 8 on the server, you have to open the SSH terminal to run the composer command. You can either use the Putty terminal or Cloudways SSH terminal as per the requirements.

Let’s start with Putty: go to the application public_html folder and type the following Laravel Composer installation command:

composer create-project — prefer-dist laravel/laravel blog

Where:

laravel/laravel: is the package for the Laravel installation.

blog: is the new directory for your new project (you can change it).

Once you have installed Laravel 8, you can enter in the new directory (blog) and execute the artisan command for the verification:

Now, go to your application path: APPLICATION-URL/laravel/public

Successfully now you can start to play with the new features of Laravel 8.0.
Laravel — The Basics — Logging (官方文件原子化翻譯筆記)
By: Ray Lee
Tags: Logging, Backend, Laravel, Documentation

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Laravel — Entendendo o Ecossistema Atual ou Quase!
By: Nando Kstro Net
Tags: Laravel Ui, Laravel Ecossistema, Laravel, Laravel Jetstream, Laravel 8

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Building laravel documentation locally
By: Semih Erdogan
Tags: Laravel Development, Laravel Documentation, Laravel

Photo by Rich Tervet on Unsplash

Laravel documentation website is great and i can find whatever i needed.

But this document pages updating almost everyday and keeping track of those changes became almost impossible for me.

For solving this issue i build laravel documentation website on my local computer and used git for getting differences between my local and remote documentation repository.

Let’s start!

Head over to github laravel docs repository https://github.com/laravel/docs.

In this repository you can see branches are the same with laravel versions (8.x, 7.x, 6.x etc.).

And also you can see all pages in “.md” format (artisan.md, blade.md etc.)

What we are going to do is, we will clone this repo and checkout branches into another folders.

Create and cd into new documentation folder

$ mkdir laravel-docs & cd laravel-docs .

. Clone branch which you want to keep track of changes.

$ git clone https://github.com/laravel/docs.git -b 8.x --single-branch 8.x

For seeing changes first you need to get latest changes from github.

$ git pull

After pulling changes from remote you may see these changes with

$ git diff HEAD@{1} `

Example output will be like this:

After this steps i was able to know latest changes about laravel documentation but after some time i’ve realised that i need changes from another branches too and checking those changes manually will take too much time.

For this reason i’ve created a script that gets all branches. With this script checking this changes got much easier. And i also add basic html page to see .md files locally.

For learning more about the script you can check github repository https://github.com/laratoolbox/laravel-local-documentation .
How to deploy Laravel APP in cPanel shared hosting
By: Manish Baral
Tags: Cpanel Shared Hosting, Laravel Deployer, Laravel, Hosting, Cpanel

Many articles that I read has wrong way of deploying Laravel application on shared hosted environment inside cPanel.

Most of them stated that uploading the project folders inside the cPanel and copy the public folder to public_html and modify the Laravel framework ( public/index.php).

I believe the following steps is the correct way to deploy and easier way to maintain continuous integration and continuous delivery.

STEP 1: Login to your cPanel

Login to you cpanel with your login credentials and then go to Advance section and inside it you will find terminal.

Note: Make sure you have SSH access from your provider

STEP 2: Install Composer

Configure your shell environment to use composer

echo 'alias composer="php -d allow_url_fopen=On /home/USERNAME/composer.phar"' >> ~/.bashrc

source ~/.bashrc

Download composer:

curl -k -O https://getcomposer.org/installer

Install composer:

php -d allow_url_fopen=On installer

STEP 3: Upload your Project

Upload you project to home directory of the cPanel file manager.

STEP 4: Run Following Commands

Lets say your app is in app folder. Go your your app folder.

composer install

to install all php dependencies if you have not uploaded vendor folder.

Then change your environmental variables in the .env file

Generate a new application key

php artisan key:generate

Migrate and seed your database as per you need.

Set the correct folder permissions

chmod -R 775 storage

STEP 5: Make your app accessible for public

Back up your public_html folder and remove it.

Then create a symlink

ln -s /home/user/app/public /home/user/public_html

Create a symlink for your storage

ln -s /home/user/app/storage/app/public /home/user/public_html/storage

Run storage link

php artisan storage:link

Your app should work now.

Usage Commands

1. Migrate Tables => `php artisan migrate` 2. Seed Database => `php artisan db:seed --class=InitDbSeeder` 3. Start Server => `php artisan serve` 4. Watch Server => `yarn watch` or `npm run watch`

Other Commands

# Turn on maintenance mode

php artisan down # Turn off maintenance mode

php artisan up # Sync composer.local with composer.json

composer update --lock # Create Model

php artisan make:model Flight # Create Model & Migration

php artisan make:model Flight -m # Create Migration

php artisan make:migration create_users_table --create=users # Update Existing Migration

php artisan make:migration add_votes_to_users_table --table=users # Create Controller

php artisan make:controller PhotoController # Composer dump

composer dump-autoload # Clear caches

php artisan cache:clear # Clear and cache routes

php artisan route:clear

php artisan route:cache # Clear and cache config

php artisan config:clear

php artisan config:cache

YOU ARE DONE! HAPPY CODING!
Laravel — The Basics — Validation (官方文件原子化翻譯筆記)
By: Ray Lee
Tags: Documentation, Backend, Laravel, Validation

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Tutorial GIS (crud) Laravel dan leaflet js
By: Eri Pratama
Tags: Tutorial, GIS, Laravel Framework, Laravel, Leaflet

in Digital and innovation at British Red Cross
Laravel — The Basics — Error Handling (官方文件原子化翻譯筆記)
By: Ray Lee
Tags: Backend, Error Handling, Laravel, Documentation

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
2 common steps to secure Laravel website that most new developers forget
By: Muhammad Osama Jahangir
Tags: Website Development, Laravel Framework, Web Development, Laravel, Software Development

Laravel is one of the most used Php framework that can make development easier but some times a single mistake by developer can cause huge security vulnerabilities. Many new Laravel developers forget these two important factors while deploying a Laravel website.

Setting a middleware properly

Most of us remember to setup Auth Middleware but its not enough if you have a multiuser system. Pages seen by Admin or superior user should not to be accessible by general authenticated users. If you have only setup Auth middleware General user can have access to admin pages.

Solutions:

Keep admin functions/routes separate from general user functions/routes and add admin middleware by creating custom Admin Middleware. If you don't want to create a separate middleware for any user than usean easier way by setting “type” field in “users” table. Assign it value at time of user Registration. Lets say Admin registers assign “type” as “admin”

Now when you return data from Controller to front end first check whether the logged in user is Admin or not only return data if the eligible user is requesting. Same will be case for any other type.

Securing the .env file

In Laravel framework all passwords and secret keys are saved in .env file. If a developer forgets to disable access to .env file for visitors than a visitor can view the .env file.

Solution:

Add these lines to your .htaccess file to prevent any website visitor from accessing the .env file.

# Hide a specific file

<Files .env>

Order allow,deny

Deny from all

</Files> RewriteEngine On

After adding these lines to your .htaccess file a general visitor will not be able to view secret website data from .env file.

Conclusion:

I know that these two steps are not enough for fully securing your website. You must do other security measures as well but these are mandatory issues that every Laravel developer must recheck before deploying the website.

For more information visit our website : www.easeonconsole.com
How to get env variable in controller or blade file
Tags: Env, Variable, Example, Laravel

How to get env variable in controller or blade file Websolutionstuff ·Dec 18, 2020

In this tutorial I will give you information how to get .env variable in controller or file many time we need to required of env variable in controller and blade file like if you are creating paypal integration then you have stored app id and secret key in env file. But if you haven’t any idea how to get it in controller or blade file.

and file like if you are creating paypal integration then you have stored app id and secret key in env file. But if you haven’t any idea how to get it in controller or blade file. So, let’s check how to get those variable data from .env file.

Syntax of env variable write:

env(‘VARIABLE_NAME’);

Example of env variable:

env(‘PAYPAL_CLIENT_ID’);

Example of Laravel Blade file

@if(env('APP_ENV') == 'local')

Match

@endif

Example of Laravel Controller

if(env('APP_ENV') == 'local')

{

echo 'Match';

}

So, it is very simple to get variable data from .env file like this.
Deploying Laravel applications in AWS Lightsail with a NGINX instance
By: Puria Golgoonnejad
Tags: AWS, Lightsail, Nginx, Laravel

Cloning your project

According to the bitnami documentation the recommended directory for your Laravel project files is:

/opt/bitnami/projects/[your-project-name]

Changing the storage directory permission

After that you cloned your project, you need to give the web server writing permission. Trust me this step could be a nightmare if you don’t do it properly.

sudo chown -R daemon:daemon /opt/bitnami/projects/[your-project-name]/storage

Do not forget to include -R flag as you might face some errors like:

The stream or file /opt/bitnami/projects/[your-project-name]/storage/logs/laravel.log could not be opened in append mode: failed to open stream: Permission denied.

Creating the NGINX configuration for your application

Now you need to create a .conf file containing the application’s HTTP server block configuration :

cp /opt/bitnami/nginx/conf/server_blocks/sample-server-block.conf.disabled /opt/bitnami/nginx/conf/server_blocks/[your-project-name]-server-block.conf

The configuration block inside the “[your-project-name]-server-block.conf” file should be something like:

server {

# Port to listen on, can also be set in IP:PORT format

listen 80 default_server;

root /opt/bitnami/projects/[your-project-name]/public;

# Catch-all server block

# See: https://nginx.org/en/docs/http/server_names.html#miscellaneous_names

server_name _;

include "/opt/bitnami/nginx/conf/bitnami/*.conf";

}

Similarly, you also need to create another .conf file containing the application HTTPS server block configuration :

cp /opt/bitnami/nginx/conf/server_blocks/sample-https-server-block.conf.disabled /opt/bitnami/nginx/conf/server_blocks/[your-project-name]-https-server-block.conf

The configuration block inside the [your-project-name]-https-server-block.conf file should be something like:

server {

# Port to listen on, can also be set in IP:PORT format

listen 443 ssl default_server;

root /opt/bitnami/projects/[your-project-name]/public;

# Catch-all server block

# See: https://nginx.org/en/docs/http/server_names.html#miscellaneous_names

server_name _;

ssl_certificate bitnami/certs/server.crt;

ssl_certificate_key bitnami/certs/server.key;

include "/opt/bitnami/nginx/conf/bitnami/*.conf";

}

Finally, you need to restart the NGINX server with the following command:

sudo /opt/bitnami/ctlscript.sh restart nginx

Congratulation!, your NGINX server is configured successfully.

Note: you still need to enter the database connection details in the .env file and also you need to run the following commands as well :

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=database_name

DB_USERNAME=user

DB_PASSWORD=pass

php artisan key:generate

php artisan migrate

Hopefully this article would help you to configure you web server easier.

Please feel free to leave a message if you see any mistake in this article.

Cheers!

Resources:
Line Breaks In Laravel Blade
Tags: PHP, Line Break, Laravel, Nl2br

I am Laravel and PHP Developer. I have also Good Knowledge of JavaScript, jQuery, Bootstrap and REST API.
Laravel .env Exposed. When it comes to host a Laravel project…
By: Mohit Mehta
Tags: Bugs, Vulnerability, Env, Laravel, Hacking

When it comes to host a Laravel project on shared hosting, many of the developers finds a difficulty. So they just apply any random solutions from different websites to make their project working without even knowing the consequence of that. Let me give one example.

One of the easiest way of Laravel hosting is move all files of public folder to root and make some changes in index.php

Once you go with above solution, you are opening doors for the hackers and attackers. Because Laravel’s base directory has many important files like .env, .htaccess etc and your web-server is also pointing to Laravel’s base directory. So these all important files can directly be accessed by URL. For example, .env file can be accessed via www.example.com/.env and it results,

.env exposed
Install PHP 7.3 in your mac OS
By: Shamshad Zaheer
Tags: PHP, Laravel, Valet

Open your terminal and check if the PHP is already installed or not.

To check currently installed php version. you can use following command in your terminal.

php -v

To install new php version use the following command.

brew install php@7.3

To uninstall php from your mac os use the following command.

brew uninstall php@7.3 — force
Change (edit/create) virtualhost for any folder on laragon
By: Md. Zahidul Islam
Tags: Laravel Development, Laravel, Virtual Host, Laragon

I have been using Laragon for few days. One of my student inspired me to move on Laragon. Actually the most valuable feature I found that virtual hosts are created automatically as soon you create a new project by clicking quick app menu.

Quick app >> Laravel

Create virtualhost by clicking quick app menu

The problem started when i imported one my previous project in laragon. I copied the folder into www folder but I can not browse that project with virtualhost. I followed a process that I created a project with a name that i am expecting and after that i removed all the folder inside that and copied my folder into that place.

This is not a proper solution. So I was looking for solution. I see

C:\laragon\etc\apache2\sites-enabled

Folder for virtualhost configuration

folder containing .conf file which has contains folder location and url.

Virtualhost configuration file

After changing configuration do not forget to restart your laragon.

Restart laragon

I think you can browse your project with your expected url.

Thanks
Most Essential Laravel Packages — Must have Packages
By: Bikram Kc
Tags: PHP, Laravel

We all know reinventing a wheel concept and Laravel makes it so easy to where we can just plug and play with various packages. Here are some of the essential Laravel Packages in my opinion:

Barryvdh: Laravel Debugbar

Link: https://github.com/barryvdh/laravel-debugbar Maatwebsite: Laravel Excel

Link: https://github.com/Maatwebsite/Laravel-Excel Spatie: Laravel Permission

Link: https://github.com/spatie/laravel-permission Intervention: Image

Link: https://github.com/Intervention/image Fruitcake: Laravel Cors

Link: https://github.com/fruitcake/laravel-cors LazyChaser: Nestedset

Link: https://github.com/lazychaser/laravel-nestedset LaravelCollective Html

Link: https://github.com/laravelcollective/html Laravel Tinker

Link: https://github.com/laravel/tinker Laravel Inertia

Link: https://github.com/inertiajs/inertia-laravel Livewire

Link: https://github.com/inertiajs/inertia-laravel
Laravel Fullcalendar CRUD Event Example
By: Hardik Savani
Tags: Fullcalendar, Laravel

Hi All,

This example is focused on laravel 8 fullcalendar example. this example will help you laravel 8 fullcalendar tutorial. Here you will learn how to use fullcalendar in laravel 8. you’ll learn laravel 8 implement fullcalendar. Alright, let’s dive into the steps.

In this example, we will simply create crud application with fullcalender so you can easily create event, edit event by drag and drop and delete event. in this example we will create events table with start, edit date and title column. then you can add, edit and delete that event with database.

Let’s follow few step to make it laravel fullcalender crud app.

Step 1: Install Laravel 8

Step 2: Create Migration and Model

Step 3: Create Routes

Step 4: Create Controller File

Step 5: Create Blade File

LINK: https://www.itsolutionstuff.com/post/laravel-8-fullcalendar-with-create-edit-delete-event-exampleexample.html
Laravel On Shared Hosting
By: Lee Mason
Tags: PHP, SEO, Cpanel, Laravel

Before we start its worth caveating this post with the message: It’s always more desirable and recommended to serve Laravel apps from bespoke hosting environment.

There are plenty to choose, from first party tools like Forge and Vapour to more general providers like Digital Ocean, AWS and GCP.

However as i find myself in a similar situation there may be times you have to deploy on a CPanel environment.

I am going to cover the usual quite simple redirect you see across the web, but more importantly a second step thats usually left out. This second step can have a massive impact on your SEO.

The Redirect

As you may of found elsewhere theres a simple redirect you can put in the root folder of your project:

# Internally rewrite all top-level requests to the public directory <IfModule mod_rewrite.c>

RewriteEngine On

RewriteRule ^(.*)$ public/$1 [L]

</IfModule>

It’s very simple and just redirects everything from the root of your site public_html down into the public folder of your Laravel project.

From there the .htaccess provided with Laravel will take over and route incoming requests.

Job done? Maybe not…

The SEO Problem

The problem with the above redirect is that it doesn’t prevent access to ALL of your urls with a /public/ prefix. So both / and /public/ will server your applications homepage!

This is obviously bad for any SEO efforts your planning to make to the site as you now have duplicate pages and on top of that if someone stumbles upon those urls its not great for users.

I spent sometime trying out redirects to prevent this from the .htaccess file itself but came up blank. In my particular case this is a CPanel server with Litespeed installed. And i know from experience its not quite 100% like for like with Apache.

The Solution

With the .htaccess approach coming up blank i went with a Middleware solution. Again this isn't ideal as its not really the applications responsibility but we are not in an ideal situation anyway.

It’s a pretty simple middleware, it looks for the public prefix and returns a 301 redirect if found. This does mean you cannot have urls that start with public but in our case this wasn't a problem:

<?php

namespace App\Http\Middleware;



use Closure;

use Illuminate\Http\Request;



class RedirectPublicFolderRequests

{

/**

* Handle an incoming request.

*

* @param \Illuminate\Http\Request $request

* @param \Closure $next

* @return mixed

*/

public function handle(Request $request, Closure $next)

{

if (strpos($request->getRequestUri(), '/public') === 0) {

return redirect()

->to($request->getSchemeAndHttpHost() . '/' . substr($request->getRequestUri(), 8))

->setStatusCode(301);

}

return $next($request);

}

}

Once again this isn’t ideal but works for our purposes.

Add this to your global middleware stack before anything else.

Note how we use the $request->getRequestUri () method and not simply $request->path() . As the path will be effected by the servers rewrites.
How To Integrate Paypal Payment Gateway In Laravel
Tags: PayPal, Payment Gateway, Example, Laravel, Integration

In this tutorial I will teach you most important topic how to integrate paypal payment gateway in laravel, payment integration is very useful and important features in e-commerce website.

Here, I am talking about paypal integration in laravel, in this tutorial i will explain you how to integrate paypal payment gateway in latest version of laravel.

PayPal is an American company operating a worldwide online payments system that supports online money transfers and serves as an electronic alternative to traditional paper methods like checks and money orders.So, follow below steps and get proper output.

Step 1 : Create new project in laravel

Step 2 : Database Configuration

Step 3 : Install Package For Paypal Using Composer

Step 4 : Configuration paypal.php file

Step 5 : Create Route

Step 6 : Create Controller

Step 7 : Create blade file for View

And you will get output of above code like below screenshot.

How To Integrate Paypal Payment Gateway In Laravel

How To Integrate Paypal Payment Gateway In Laravel

And if you like this post then don’t forgot to “Claps”.

Thanks for Reading !!
Laravel 8.* + Backpack + CRUD- Article with tags
By: Lyubomir Filipov
Tags: Backpack, Articles With Tags, Crud, Laravel

In order to proceed you should have:

- Laravel installed + Backpack admin (teaching purposes)

- Tags CRUD created

- virtual host ready for you

- xampp setup or other web server

- composer installed

We will define what an Article consists of

- title — text

- content — text — RichTextEditor

- tags (many available) — select with multiple options

New tutorial to add file upload to the artilce

- image (one image) — image upload

# STEP 1. create migration for many to many

php artisan make:migration:schema create_article_tags_table --model=0 --schema="article_id:integer:unsigned,tag_id:integer:unsigned"

This will create a new file in your migrations folder:

Create Article Tags migration

Remove the timestamp from the migration and then run:

php artisan migrate

We have now the table prepared many to many connections

#Step 2 — create article table

php artisan make:migration:schema create_articles_table --model=0 --schema="title:string,content:longText"

and then

php artisan migrate

#Step 3 — Create crud for Articles

php artisan backpack:crud article

#Step 4 — edit Article model

Add the following function

public function tags()

{

return $this->belongsToMany(Tag::class, 'article_tags','article_id', 'tag_id');

}

This makes the connection between articles and tags stating that one article could belong to many tags using the article_tags table for the reference.

Reference will be made by adding a new row for every tag.

#Step 5 — Alter Article controller

Add new function to the controller

private function getFieldsData($show = FALSE) {

return [

[

'name'=> 'title',

'label' => 'Title',

'type'=> 'text'

],

[

'name' => 'content',

'label' => 'Content',

'type' => ($show ? "textarea": 'ckeditor'),

],

[ // Select2Multiple = n-n relationship (with pivot table)

'label' => "Tags",

'type' => ($show ? "select": 'select2_multiple'),

'name' => 'tags', // the method that defines the relationship in your Model // optional

'entity' => 'tags', // the method that defines the relationship in your Model

'model' => "App\Models\Tag", // foreign key model

'attribute' => 'name', // foreign key attribute that is shown to user

'pivot' => true, // on create&update, do you need to add/delete pivot table entries?

]

];

}

Update setup method

Add new method at the bottom of the file — setupShowOperation

protected function setupShowOperation()

{

// by default the Show operation will try to show all columns in the db table,

// but we can easily take over, and have full control of what columns are shown,

// by changing this config for the Show operation

$this->crud->set('show.setFromDb', false);

$this->crud->addColumns($this->getFieldsData(TRUE));

}

Final result:

Menu is updated

Listing is present

Add is updated
How to add multiple where clauses using Laravel Eloquent
By: Harvie Rees
Tags: Developer, Laravel Eloquent, Code, Laravel

Check out this post on the devdojo.com website!

It is a post on How to add multiple where clauses using Laravel Eloquent 🔥!

To make things even better you can use this referral link to get a free $100 credit that you could use to deploy your virtual machines and test the guide yourself on a few DigitalOcean servers:

Digital Ocean $100 Free Credit

Link to the post:

https://devdojo.com/bobbyiliev/how-to-add-multiple-where-clauses-using-laravel-eloquent

I strongly encourage everyone to go ahead and check out the devdojo.com website, there’s a lot of valuable content there.
What is Laravel Sail and how to get started?
By: Harvie Rees
Tags: Developer, Laravel Eloquent, Code, Laravel

Check out this post on the devdojo.com website!

It is a post on What is Laravel Sail and how to get started? 🔥!

To make things even better you can use this referral link to get a free $100 credit that you could use to deploy your virtual machines and test the guide yourself on a few DigitalOcean servers:

Digital Ocean $100 Free Credit

Link to the post:

https://devdojo.com/bobbyiliev/what-is-laravel-sail-and-how-to-get-started

I strongly encourage everyone to go ahead and check out the devdojo.com website, there’s a lot of valuable content there.
Date validation in Laravel
By: Nguyễn Tuấn Phúc
Tags: Laravel

Laravel provides many convenience ways to validate date

From document let’s take after for example

> The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function in order to be converted to a valid DateTime instance:

'start_date' => 'required|date|after:tomorrow'

Instead of passing a date string to be evaluated by strtotime , you may specify another field to compare against the date:

'finish_date' => 'required|date|after:start_date'

However, how to validate with a custom format?

Luckily, we have date_format validator

'start_date' => 'required|date_format:Y-m-d H:i:s|after:' . date('Y-m-d H:i:s')

With this format, we can put anything we need there to validate
Debug Laravel query with parameters
By: Nguyễn Tuấn Phúc
Tags: Sql Debug, Laravel

This will apply for both Eloquent and Query Builder - DB

To debug your sql in Laravel you can you

$userQuery = User::where('email', 'example@email.com'); dd($userQuery->toSql());

The result

"select * from `users` where `email` = ?"

To view full sql with parameter, use this piece of code

$userQuery = User::where('email', 'example@email.com'); $fullQuery = vsprintf(str_replace('?', '%s', $userQuery->toSql()),

collect($userQuery->getBindings())->map(function ($binding) {

return is_numeric($binding) ? $binding : "'{$binding}'"; })->toArray()

);



dd($fullQuery);

The result