Learn How to Use Laravel Enum Casting

Understand how to implement enum model attribute casting in Laravel 9 for efficient data handling.

If you’re looking to use the enum data type in Laravel, you can do so easily with the help of enum model attribute casting. In this post, we’ll walk you through a step-by-step example to show you how to use enums in Laravel and cast them to a model attribute.

First, you’ll need to create a migration with a string column called "status" and a default value of "pending". Then, you can create a model and set the cast to your enum class. With this approach, you won’t have to create a new migration every time you want to add a new enum value to your table.

Laravel 9 has introduced enum model attribute casting, which makes it easier than ever to use enums in your application. With the help of an enum class and model casting, you can easily set up your table with specific enum values.

In this example, we’ll guide you through the process of creating a migration with a string column, creating a model with a cast to your enum class, and creating an enum class with specific values. Follow along with our step-by-step example to learn how to use Laravel enum attribute casting today.

Step 1: Install Laravel

If you haven’t already created a Laravel app, run the following command to install Laravel:

composer create-project laravel/laravel example-app

It will install new laravel app inside example-app folder. For further commands, go inside the example-app folder. There are many other ways to install the laravel application. Click on this link to visit Laravel installation documentation.

Step 2: Create Laravel Migration

Create a migration for the "enquiries" table with name, email, phone and status columns, as well as a model for the enquiries table. run the following command to create migration:

php artisan make:migration create_enquiries_table

Update the migration file with the following code:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('enquiries', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->bigInteger('phone');
            $table->string('status')->default('pending');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('enquiries');
    }
};

Now, we are ready with our migration script. Run the following command to create the "enquiries" table:

php artisan migrate

Note that, we created the table with "status" value as "pending" by default.

Step 3: Create Enum Class

Create the Enums folder and EnquiryStatusEnum.php class inside the Enums to define all enum values as follows:

namespace App\Enums;

enum EnquiryStatusEnum: string {
    case Pending = 'pending';
    case InProgress = 'in-progress';
    case Closed = 'closed';
}

Step 4: Create Model

Now, we need a model file for our enquiries table. To create a model, run the following command:

php artisan make:model Enquiry

It will create Enquiry.php file inside the app/Models folder. Change the model file as follows:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Enums\EnquiryStatusEnum;

class Enquiry extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'email', 'phone', 'status'
    ];

    protected $casts = [
        'status' => EnquiryStatusEnum::class
    ];
}

Here, we defined a $casts variable, which will cast the status variable with EnquiryStatusEnum class.

Step 5: Create Controller

Now, create a controller file using the following command:

php artisan make:controller EnquiryController

It will create the EnquiryController.php file inside the app/Http/Controllers folder. Write the following code inside index() method to create item records with an array and access as an array:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Enquiry;
use App\Enums\EnquiryStatusEnum;

class EnquiryController extends Controller
{
    public function index()
    {
        $input = [
            'name' => 'Test User',
            'email' => 'test@example.org',
            'phone' => 6358465465
            'status' => EnquiryStatusEnum::Active
        ];

        $enquiry = Enquiry::create($input);

        dd($enquiry->status, $enquiry->status->value);
    }
}

In above code, we have added a new entry inside the enquiries table and right after that we displayed the enquiry status.

Step 6: Create Route

To create a route for testing our code, add the following lines to routes/web.php file:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EnquiryController;

Route::get('enquiry', [EnquiryController::class, 'index']);

Step 7: Run the Laravel app

To run the laravel app, use the following command:

php artisan serve

Open your web browser and enter the following URL to view the app output:

http://localhost:8000/enquiry

You can see the database output and print variable output:

App\Enums\EnquiryStatusEnum {#1781
    name: "InProgress"
    value: "in-progress"
}

in-progress

You can see the database output, which is showing casted values from EnquiryStatusEnum. And second parameter is value output, which is showing it’s corresponding string value "in-progress".

With these simple steps, you can easily use enum in Laravel without the need for constant migrations.

Install React JS with Laravel Breeze

Guide to installing Laravel Breeze with React JS scaffolding via Inertia for building modern applications.

In this React JS tutorial, we learn to install Laravel Breeze with React JS over Laravel Application. Laravel Breeze come equipped with out-of-the-box scaffolding for new Inertia applications, making them the quickest and easiest way to get your Inertia project off the ground with React Js.

For this post, we are using Laravel Breeze. This minimal implementation includes login, registration, password reset, email verification, password confirmation, and a basic “profile” page for updating user information.

Laravel Breeze comes equipped with simple Blade templates styled with Tailwind CSS. However, if you prefer to scaffold your application using React JS and Inertia JS, Laravel Breeze can do that too.

In addition to being an excellent starting point for a new Laravel project, Laravel Breeze is also a great choice for projects that want to elevate their Blade templates using Laravel Livewire.

Install laravel project and setup database

First install a fresh new Laravel application from the composer using the following command,

composer create-project laravel/laravel inertia-react

It will create the laravel project folder named inertia-react .

Now, you have to connect the laravel app to the database. Go inside this folder and open .env to change the database connection details as follows,

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_username
DB_PASSWORD=database_password

After changing the connection details, run all migrations for the project using the following command,

php artisan migrate

Install Laravel Breeze over Laravel

Once you ready with the Laravel installation, you can proceed with Laravel Breeze installation using Composer using the following command,

composer require laravel/breeze --dev

Once you’ve installed the Laravel Breeze package using Composer, it’s time to run the breeze:install Artisan command as follows,

php artisan breeze:install

This command will publish all the necessary authentication resources, including views, routes, controllers, and more, directly to your application.

Laravel Breeze publishes its code directly to your application, giving you complete control and visibility over its features and implementation. This allows you to easily customize and tailor the authentication experience to fit your unique needs.

If you want to use an Inertia stack with React JS in your Laravel Breeze application, simply specify “react” as your desired stack when running the breeze:install Artisan command as follows,

php artisan breeze:install -react

Once the scaffolding is installed, be sure to compile your application’s frontend assets to ensure proper functionality:

npm install && npm run dev

With the initial setup complete, it’s time to test your application’s authentication functionality. Simply navigate to the /login or /register URLs in your web browser to get started.

All of Laravel Breeze‘s routes are defined in the routes/auth.php file, making it easy to modify or customize the authentication routes as needed.

Using Laravel to upload a file

Learn how to handle file uploads in Laravel, including validations and best practices.

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

Dive into the building blocks of JavaScript, including unicode, case sensitivity, semicolons, and more.

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

Resolve the “libpangox-1.0.so.0” shared library error in Anydesk on Ubuntu 22.04 LTS with this easy step-by-step fix and download instructions.

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

What is libpangox library?

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.

Install the library

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

sudo 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 this error 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

You need to manually download the .deb file using wget command. This package is available to many package libraries. I have downloaded it from Debian Package Library.

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

Install the downloaded .deb file using apt command as follows,

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

Step3: Restart the AnyDesk service

After successful installation, restart the anydesk service.

sudo service anydesk restart

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