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.

Getting started with ReactJS

Setting up a local environment is recommended way to learn ReactJS because the local setup allows you to complete the tutorial using your choice of editor, use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production.

Setting up a local environment is recommended way to learn ReactJS because the local setup allows you to complete the tutorial using your choice of editor, use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production.

Let’s start with creating a new ReactJS application.

Create React App

Creating React App is a comfortable environment for learning and building an application in React.

There are few prerequisites for creating a React app as follows,

  • Node.js >= 14.0.0
  • npm >= 5.6

If above requirements are satisfied, you can run the following command to create a new react application,

npx create-react-app my-react-app

You can change my-react-app to anything you want to name your app.

The create-react-app command will set up everything you need to run a React application. Now you are ready to run your first real React application! Go to your application directory using the following command,

cd my-react-app

Now, run the following command inside your application directory to run your application,

npm start

It will compile your application and open it in the new browser window or tab. If not, you can open your browser and write localhost:3000 in the address bar. Your application will look like screenshot below,

If you check your command window, it will show the following output,

You can see that command window is also providing command to create a production build for your application.

Using React JS in the HTML File

We will learn to use ReactJS directly in the HTML file. There are some prerequisites to adding ReactJS script inside the HTML code.

Now that we know what React JS is, we can start with different usage of ReactJS. If you don’t know what React JS is, read the Getting Started with ReactJS.

In this article, we will learn to use React JS directly in the HTML file. There are some prerequisites to adding React JS script inside the HTML code. We need to include the following three javascript in the head section of the HTML file.

The first two allow us to write ReactJS code in our JavaScripts, and Babel Js will allow to write JSX syntax and ES6 in older browsers.

Follow the below steps to add react JS compnent to the HTML file.

Add the DOM container to mount ReactJS Component

Embedding React JS in HTML differs slightly from what we have done with React Js App. In a standard React Js app, the root element in the index.html is the container that mounts the React Js app. Similarly, we need any element to mount our react JS component in HTML file as below,

<div id="example"></div>

In above code, we have added an element with id example in HTML file.

Add required JS files to run ReactJS

We want to run a React app in an HTML file, where no node_modules to provide React Js dependencies. Therefore, we must add React dependencies by including React script tags in the HTML document as below,

<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>

In above code, we have included the required React JS scripts, which are required to execute the React JS code.

React Js code returns JSX. So, we also need Babel JS to transform that JSX as below,

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

Write ReactJS code in HTML

Now, our HTML file is ready for react JS code. But, we have to add our react JS code in text/babel script tag as babel can transpile our react JS code as below,

<script type="text/babel">
  function Hello() {
    return <h1>Hello World!</h1>;
  }
  ReactDOM.render(<Hello />, document.getElementById('example'))
</script>

Example

The complete code of using React JS in the HTML file is as follows,

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
      function Hello() {
        return <h1>Hello World!</h1>;
      }
      ReactDOM.render(<Hello />, document.getElementById('example'))
    </script>
  </body>
</html>

This way, we can use ReactJS for testing purposes. But for production use, we have to set up a React environment.

ReactJS Introduction

ReactJS is one of the most popular JavaScript front-end libraries for building user interfaces with a strong foundation. It has a robust and rapidly growing developer community and a declarative, efficient, and flexible library for building reusable UI components. It is an open-source, component-based front-end library responsible only for the application view layer. 

ReactJS is one of the most popular JavaScript front-end libraries for building user interfaces with a strong foundation. It has a robust and rapidly growing developer community and a declarative, efficient, and flexible library for building reusable UI components. It is an open-source, component-based front-end library responsible only for the application view layer. 

Initially, it was developed by Jordan Walke, a software engineer at Facebook and maintained by Facebook. Later, it was used in other Facebook products like WhatsApp & Instagram. Facebook implemented ReactJS in its newsfeed section in 2011, but it was released to the public in May 2013.

The main objective of ReactJS is to develop interactive User Interfaces (UI) with the help of virtual DOM (JavaScript object) to improve application performance because the JavaScript virtual DOM is faster than the regular DOM because, it only changes individual DOM elements instead of reloading complete DOM every time. It uses component and data patterns that improve readability and helps to maintain larger apps.

The components are the heart of all React applications. These component are used to make a React application. Each component is responsible for outputting a small, reusable piece of HTML code and can be nested with other components to allow complicated applications.