Using Laravel to upload a file

Uploading a file in any programming is a challenge. So, we focus on uploading a file and some validations to use with file upload using Laravel.

Uploading a file in any programming is a challenge. In this post, we focus on uploading a file and some validations to use with file upload using Laravel.

To upload a file using Laravel, you can follow these steps:

Create a new form in your Laravel view with an input field for the file:

<form method="POST" action="{{ route('file.upload') }}" enctype="multipart/form-data">
    @csrf

    <input type="file" name="file">

    <button type="submit">Upload</button>
</form>

In above code, we have added file.upload route as an action of the form. So, we need to define this route in routes/web.php file. This route should point to the controller method that will handle the file upload.

The following code will define a new route in your routes/web.php file:

Route::post('/file/upload', [App\Http\Controllers\FileController::class, 'upload'])->name('file.upload');

Above code has defined a route, which points to the upload method of the FileController. So, create a new controller FileController and method upload inside that to handle the file upload as follows:

class FileController
{
    public function upload(Request $request)
    {
        // Validate the uploaded file
        $request->validate([
            'file' => 'required|file|max:1024', // limit file size to 1 MB
        ]);

        // Store the uploaded file in the storage/app/public directory
        $path = $request->file('file')->store('public');

        // Generate a URL for the uploaded file
        $url = Storage::url($path);

        // Redirect back with a success message
        return back()->with('success', 'File uploaded successfully: ' . $url);
    }
}

In the upload() method, we first validate that the uploaded file meets our requirements. So, we have added some validations for our file. These validations are as follows:

required:

The field under this validation must be present in the input data and must not empty. A field is “empty” if it meets one of the following criteria:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with no path.

file:

The field under this validation must be a successfully uploaded file.

max:1024:

The field under this validation must be less than or equal to a 1024 bytes. Here, 1024 is value of file size. You can change it according to your requirements.

We then use the store() method on the uploaded file to store it in the storage/app/public directory. This directory is publicly accessible, so we can generate a URL for the file using the url() method on the Storage facade. Finally, we redirect back to the form with a success message that includes the URL of the uploaded file.

You can now test the file upload functionality by navigating to the form and selecting a file to upload. If the file meets the validation requirements, it will be uploaded and a success message will be displayed. You can then access the uploaded file at the generated URL.

JavaScript and it’s Lexical Structure

Learn building blocks of javascript like unicode, case sensitivity, semicolons, comments, white space, literals, identifiers, and reserved words to understand the lexical structure of it.

To understand the structure of JavaScript, you need to learn the following building blocks of it: Unicode, case sensitivity, semicolons, comments, white space, literals, identifiers, and reserved words.

Nowadays, javascript are used in every websites in a different forms. Frameworks like ReactJS, NextJS, NodeJS, VueJS, etc. become more popular to meet the market demand of rapid development. In such cases, understand the lexical structure of it becomes more important for every developer, who works with it.

Unicode

You can use Unicode in JavaScript. So, you can use Emojis as variable names and write identifiers in any language, for example, Japanese or Chinese, with some rules. 

If you want to know whether your Unicode variable is acceptable or not, you can check it at https://mothereff.in/js-variables.

Case sensitivity

JavaScript is case-sensitive like many languages. So, a variable name written in a lower case format is different from the same variable name written in a camel case format.

Semicolons

JavaScript has a very C-like syntax, and you might see lots of code samples that feature semicolons at the end of each line.

Semicolons are not mandatory in JavaScript, and it does not have any problem that does not use them. Many developers, coming from languages that do not have semicolons, also started avoiding using them in JavaScript code.

It goes to personal preference and your programming behavior. If you are using those languages where semicolons are mandatory, you can use the same behavior for your JavaScript code.

Comments

Using comments helps us to understand code and its purpose. Each programming language has its own set of syntax when it comes to writing comments.

You can use two kinds of comments in JavaScript:

Single-line comments: Single-line comments begin with //. It will ignore all the things immediately after // syntax until the end of that line. It is also known as inline comments.

// Single-line comment

Multi-line comments: Multi-line comments begin with /* and end with */. You can write as many lines as you want in between these syntaxes.

/* Multi-line
Comment */

Usually, most developers use /* and */ syntax to writing multi-line block comments as JavaScript does not give any error. But the standard way to use multi-line comments in JavaScript is to use block comments as follows;

  1. Start with /** in a blank line.
  2. End with */ at the end line.
  3. Use * at the beginning of each line between the start and the end.
/**
 * Multi-line comment as
 * block comments
 */

White space

JavaScript does not consider white space meaningful like Python. You can add spaces and line breaks in any fashion.

In practice, you will most likely keep a well-defined style of indentation and adhere to what people commonly use.

Literals

We define as literal a value that is written in the source code, for example, a number, a string, a boolean, or also more advanced constructs, like Object Literals or Array Literals:

Identifiers

An identifier is a sequence of characters to identify a variable, a function, or an object. There are specific rules for identifiers as follows,

  • It should start with a letter (it could be any allowed character like emoji 😄 or Unicode words), the dollar signs $, or an underscore _.
  • It can contain digits.

Reserved words

You cannot use reserved JavaScript words as identifiers. Some of the reserve words are as follows,

break
do
instanceof
typeof
case
else
new
var
catch
finally
return
void
continue
for
switch
while
debugger
function
this
with
default
if
throw
delete
in
try
class
enum
extends
super
const
export
import

These reserved words are JavaScript functions or variables, which are used for different operations using JavaScript.

Solved – error while loading shared libraries: libpangox-1.0.so.0: Anydesk on Ubuntu 22.04 LTS

After successfully upgrading from Ubuntu 20.04 LTS to 22.04 LTS, most of the applications are working perfectly. But, some of the applications behave unusually. Such as, I tried to run the Anydesk application, but it doesn’t launch/start. when I checked the status service, the AnyDesk service was failed and the reason for failing is mentioned in the below error message,

anydesk: error while loading shared libraries: libpangox-1.0.so.0: cannot open shared object file: No such file or directory

libpangox-1.0.so.0 is a library used for text layout and rendering the text. Most of the work on Pango-1.0 was done using the GTK+ widget toolkit as a test platform.

So, I ran the command to install it using the apt as follows,

apt install libpangox-1.0-0

But, it gives me the following error,

Package libpangox-1.0-0 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

So, from that we can understand that, libpangox-1.0.so.0 can’t be installed from apt or apt-get. We need to install it manually.

Use the following steps to install libpangox-1.0.so.0 manually,

Step 1. Download the libpangox-1.0 package

wget http://ftp.us.debian.org/debian/pool/main/p/pangox-compat/libpangox-1.0-0_0.0.2-5.1_amd64.deb

Step2: Install the package using apt

sudo apt install ./libpangox-1.0-0_0.0.2-5.1_amd64.deb

Step3: Restart the AnyDesk service

sudo service anydesk restart

After these steps, if you check the AnyDesk service status, it will show active (running).

What is Middleware and how to create one in Laravel?

It’s best to envision middleware as a series of “layers” for HTTP requests that must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application. It’s best to envision middleware as a series of “layers” for HTTP requests that must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

For example, Laravel includes a middleware that verifies the authenticity of the user of your application. If the user is not authenticated, the middleware will redirect the user to your application’s login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

To perform different tasks, we can develop many middlewares besides authentication. For example, a logging middleware might log all incoming requests to your application. 

Laravel framework has included many middlewares, including middleware for authentication and CSRF protection. All of these middlewares are located in the app/Http/Middleware directory.

To create a middleware, we can use the following command,

php artisan make:middleware <middleware-name>

For example, if we want to create a middleware for checking transactions, we can run the following command,

php artisan make:middleware CheckTransaction

 After successful execution of the command, a middleware class will be created under the app/Http/Middleware directory.

In this class, we can define methods to check transactions. If the transaction is not completed, we can redirect the user back to the failed transaction page. However, on the successful transactions, we can allow users to proceed to the next page.

<?php
 
namespace App\Http\Middleware;
 
use Closure;
 
class CheckTransaction
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->input('status') !== 'completed') {
            return redirect('transaction-failed');
        }
 
        return $next($request);
    }
}

As you can see, if the transaction status does not set to “completed”, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application.

To pass the request deeper into the application (allowing the middleware to “pass”), you should call the $next callback with the $request.

Geocoding with Python – Convert any address to a geographic location

Learn how to work with geocoding APIs to receive location data from addresses and plot maps of your customer’s location.

Most of the time, datasets are incomplete and often require pre-processing to make them usable. Imagine, We have some datasets with only an address column without latitude and longitude columns, and we want to represent this data geographically. To do that, we need to add geographic information to these data. These cannot be possible manually. We have to create a script to convert all those addresses to geographic information – Latitude and Longitude – to map their locations, which is known as Geocoding.

Geocoding is the computational process of transforming a physical address description to a location on the Earth’s surface (spatial representation in numerical coordinates)

Wikipedia

In this article, I will show you how to perform geocoding in Python with the help of Geopy library. Geopy has different Geocoding services that you can choose from, including Google Maps, ArcGIS, AzureMaps, Bing, etc. Some of them require API keys, while others can be accessed freely.

To perform geocoding, we need to install the following Geopy library using pip,

pip install geopy

Geocoding Single Address

In this example, we use Nominatim Geocoding service, which is built on top of OpenStreetMap data.

Let us Geocode a single address, the Taj Mahal in Agra, India.

locator = Nominatim(user_agent="myGeocoder")
location = locator.geocode("Taj Mahal, Agra, India")

First line of the above code will create locator that holds the Geocoding service, Nominatim. In second line, we call geocode method of the locator service and pass any address to it, in this example, the Taj Mahal address.

print("Latitude = {}, Longitude = {}".format(location.latitude, location.longitude))

Above line will print out the coordinates of the location we have created.

Latitude = 48.85614465, Longitude = 2.29782039332223

That’s it.

So, the complete code will look like this,

import geopy
from geopy.geocoders import Nominatim
from geopy.extra.rate_limiter import RateLimiter

locator = Nominatim(user_agent="myGeocoder")
geocode = RateLimiter(locator.geocode, min_delay_seconds=1)

address = "Taj Mahal, Agra, India"
location = locator.geocode(address)

print("Latitude = {}, Longitude = {}".format(location.latitude, location.longitude))

Now, try some different addresses of your own.