Get auth user without sanctum middleware – Laravel

In order to get an authentication user without using sanctum middleware in Laravel, you just need to pass the string “sanctum” in auth() method.

Auth sanctum without middleware

Following route goes in the “routes/api.php” file:

# routes/api.php

Route::post("/auth-without-sanctum", function () {
    return auth("sanctum")->user();
});

Auth sanctum with middleware

If you do not want to use the “sanctum” string in auth() method, then you need to wrap your route inside sanctum middleware. Like this:

Route::group([
    "middleware" => ["auth:sanctum"]
], function () {

    Route::post("/auth-without-sanctum", function () {
        return auth()->user();
    });
    
});

Generate API Token

In order to check if the above code is working fine, we need to call an AJAX with authorization token. To create an authorization token (just for testing), we will use the following code:

# app/Http/Controllers/UserController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;
use App\Models\User;

class UserController extends Controller
{
    public function generate_token()
    {
        $user = DB::table("users")
            ->where("email", "=", "adnan@gmail.com")
            ->first();

        if ($user == null)
        {
            $id = DB::table("users")
                ->insertGetId([
                    "name" => "Adnan",
                    "email" => "adnan@gmail.com",
                    "password" => password_hash("adnan", PASSWORD_DEFAULT),
                    "created_at" => now()->utc(),
                    "updated_at" => now()->utc()
                ]);
        }
        else
        {
            $id = $user->id;
        }

        $user = User::where("id", "=", $id)->first();

        $token = $user->createToken("adnan-tech.com")->plainTextToken;
        dd($token);
    }
}

createToken(secret_string) method accepts a secret string that will be used to generate plain text tokens. You can write any string you want. Copy the value of $token variable and use it in AJAX request later in this tutorial.

Note: If you face an error while generating a token, run the following command in your terminal:

php artisan install:api

It will ask you to add Laravel\Sanctum\HasApiTokens trait in your User model. You can add it in the following way:

# app/Models/User.php

...
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens;
    
    ...
}

Learn more about Laravel sanctum from their official documentation.

AJAX with authorization header token

We are calling a simple AJAX request to this API route and passing the token value after “Bearer ” (notice the space).

var ajax = new XMLHttpRequest()
ajax.open("POST", "api/auth-without-sanctum", true)
ajax.setRequestHeader("Accept", "application/json")
ajax.setRequestHeader("Authorization", "Bearer 1|EovaNhClZ1DBrwEMRasAgpfZc7AqNF5yNaBGP76U1be5a11f")

ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText)
    }
}

ajax.send()

Open your browser inspect element and goto “Network” tab, you will see the user object in “Preview”.

Chrome inspect element network - Laravel get authenticated user without using sanctum middleware
Chrome inspect element network

Now try commenting out the line that sends authorization header in AJAX request. You will receive an empty or null response (make sure the API route is not wrapped in auth:sanctum middleware).

Error: Route [login] not defined

If you get an error “Route [login] not defined”.

Route [login] not defined - Laravel
Route [login] not defined – Laravel

Then it can also be fixed by adding the following 2 headers with your AJAX request.

ajax.setRequestHeader("Accept", "application/json")
ajax.setRequestHeader("Authorization", "Bearer 1|EovaNhClZ1DBrwEMRasAgpfZc7AqNF5yNaBGP76U1be5a11f")

And then set the name “login” to your login route.

// web.php

Route::get("/login", function () {
  return view("login");
})->name("login");

More

Learn how to fix 403 forbidden error on Laravel storage

This is how you can get an authenticated (auth() method) user in Laravel without using sanctum middleware.

File Manager in Laravel and React JS

A file manager web app is created in Laravel and React JS. We offer free 10 MB storage so you can test this script. Test it before you buy it. Easy deployment, you can just buy and upload the files on your server. Further instructions for deployment are in the file “README.md”. Check our tutorial if you need help in deployment.

We are using CloudBox Lite HTML template for this project.

Demo

Features

1) Authentication

I am using Laravel Sanctum API for handling authentication. It creates a token for each user and sends it in headers in AJAX requests. It is also useful so if you want to develop a mobile application for it, you can use the same authentication system. Because session authentication does not work on mobile.

2) Files and Folders

User can create as much folders as he wants and he can upload as much files as he wants unless his storage gets full. There is unlimited level of folder nesting just like in your computers, you can create folders and create folders inside it.

3) Rename

You can rename files and folders any time you want. You can also set the same name of different files in the same folder.

4) Private or public files

While uploading files, you can set if the file is publicly visible to other users. Or will it be only for you. You can share publicly available files with others.

User can change from public to private any time. Public files are saved in storage so they can be accessed by other users. While private files are saved in database in BLOB format. So they can only be accessible by the user who uploaded it.

5) Trash can

If you delete the file or folder by accident, it won’t be deleted permanently. It will be moved to trash where it remains unless you delete it. From trash can delete the file permanently or you can restore it. If you restore it, it will go to the same folder where it was before.

6) Share files

You can share files with other users as well if the file is public. While sharing file you can also set if the other user can just read it, or if he can modify the content of the file. Only text and source code file’s (txt, php, html, css, js, java, c, cpp, py, go, sql) content can be modified.

7) Realtime Collaboration

User can allow other’s to change the content of file without having to refresh the page. File owner can give write permission to a user and he will be able to edit the file. This is very useful for teams. Programmers can use this feature to work on the same project.

Making collaboration realtime using Node JS - File manager in Laravel and React JS
Making collaboration realtime using Node JS – File manager in Laravel and React JS

8) Profile

User can manage his personal information from his profile page. He can edit his name, phone and profile image. When user uploads a new profile image, we delete his old profile image. So only 1 image of user is saved in file system. The profile image is displayed when he shares a file with someone and also when someone adds him in his contact list.

9) Change Password

User can change his password. For that, he needs to enter his current password first. This is to prevent any other person to change his password. Passwords are stored using password_hash() PHP function that generates a store hash. It is a one-way hash, which means that once hashed, it cannot convert back to plain text. So even if someone sees your database, he won’t be able to tell the user’s passwords.

10) Email Settings

Now user can control when he wants to receive an email. Right now we are giving him 2 options:

  1. When someone add me in his contact list.
  2. When someone shares a file with me.

11) Contact List

If there are some people with whom you have files frequently. Then you do not need to type their email address everytime you share the file with them. Just add them in your contact list and next time you try to share a file with them, you will see a dropdown list with all your contacts. You can just pick the contact and hit “Share” button.

You can also see all the files you have shared with specific person from contact list.

How to compress image in PHP

Previously, I wrote an article on how to compress images in Node JS. In this article, we will discuss how you can compress an image in PHP.

Let’s say you have an image named “image.png”. The following code will compress the file by half:

$source = "image.jpg";
$destination = "image-min.jpg";
$quality = 50;

$info = getimagesize($source);
$image = null;

if ($info["mime"] == 'image/jpeg')
{
    $image = imagecreatefromjpeg($source);
}

else if ($info["mime"] == 'image/gif')
{
    $image = imagecreatefromgif($source);
}

else if ($info["mime"] == 'image/png')
{
    $image = imagecreatefrompng($source);
}

if ($image != null)
{
    imagejpeg($image, $destination, $quality);
    echo "Image compressed";
}

Explanation:

  • Line [1-3]: Setting the source and destination path. Also, the quality of the compressed image. It will be between 0 and 100. 0 means fully compressed and 100 indicates the original quality (although the file size will be reduced a little even on 100).
  • [5, 6]: getimagesize will return the size and mime type of the image. We will be needing the mime type only.
  • [8-21]: Creates a new image object based on file mime type.
  • [23-27]: If any of the supported image types match, create a JPEG image from source to destination along with the quality of the new image. If the source and destination paths are the same, the original image will be replaced by the compressed image. That is why we are using a different name for the destination image.

Why use JPEG for compressed image

You might be wondering why while creating an image object, we are checking the mime type of image. But on compressing the image we are only using imagejpeg that creates a JPEG file. We use JPEG (Joint Photographic Experts Group) for image compression for the following reasons:

  1. Compression: JPEG decreases the file size a lot without losing the quality of the image. You won’t see much difference in quality from the original to the compressed image but the file size will be much less than the original one.
  2. Custom quality: You can set the quality of your choice from 0 to 100.
  3. User experience: When the user opens a JPEG file and if it is too large, it will first load the lower quality version of the image, which is usually a grayscaled image. Then it loads the image in its original colors. This is pretty useful on slow internet.

Laravel

If you are working in Laravel, you might be facing difficulty because Laravel uses separate “storage” folder for handling all user uploaded files. Also, it creates a symbolic link to the public folder. So it gets a little confusing for developers on how to read image from storage and save the compressed image on storage.

Just change your source and destination variables to the following:

$source = base_path("public/storage/image.jpg");
$destination = base_path("storage/app/public/image-min.jpg");

To get the mime type of an image in Laravel, you can use the following code:

$file = request()->file("image");

if ($file->getClientMimeType() == 'image/jpeg')
{
    //
}

Complete code for Laravel developers will be:

if (request()->file("image"))
{
    $file = request()->file("image");

    $file_path = "images/" . $file->getClientOriginalName();
    $file->storeAs("/public", $file_path);

    $source = base_path("public/storage/" . $file_path);
    $destination = base_path("storage/app/public/" . $file_path);
    $quality = 50;

    // $info = getimagesize($source);
    $image = null;

    if ($file->getClientMimeType() == 'image/jpeg')
    {
        $image = imagecreatefromjpeg($source);
    }

    else if ($file->getClientMimeType() == 'image/gif')
    {
        $image = imagecreatefromgif($source);
    }

    else if ($file->getClientMimeType() == 'image/png')
    {
        $image = imagecreatefrompng($source);
    }

    if ($image != null)
    {
        imagejpeg($image, $destination, $quality);
        return "Image compressed";
    }
}

Note: Only the source and destination paths are changed and the way image mime type is get.

With that said, this concludes my article on how to compress an image in PHP. If you face any problem in following this, kindly do let me know.