Retrieve Laravel User from a Fetch Request

Attempting to extract the active user from a fetch request to my backend. Here is my front-end code:

let apiToken: string | null = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

fetch('http://192.168.0.6:8000/api/testURL', {
    method: "POST",
    //@ts-ignore
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json, text-plain, */*',
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': apiToken
    },
    credentials: 'same-origin',
    body: JSON.stringify(data)
})
.then(function(response): void {
    console.log(response);
})
.catch(function(err): void {
    console.log(err);
});

The CSRF token in a meta tag is generated from csrf_token();

Here is my backend code:

Route::post('/testURL', function(Request $request) {

    $status = $request->input('status');
    $comment = $request->input('comment');
    $prospectType = $request->input('prospectType');
    $leadId = $request->input('leadId');
    $requestUser = $request->user();

    return response()->json([
        'status' => $status,
        'comment' => $comment,
        'prospectType' => $prospectType,
        'leadId' => $leadId,
        'user' => $requestUser
    ]);
});

After making the API call, the 'user' field shows as null.

Attempts with Auth::user() and Auth::id() also result in null.

Tried using Sanctum for a validation token, but applying an auth:sanctum middleware led to a 302 redirect.

(The same redirection occurs when applying 'auth' to a non-Sanctum token'd request).

Main goal amidst these challenges: Ensure user ID validation when sending the request from frontend to backend.

Answer №1

After spending five long hours trying to figure it out, I finally discovered the problem with the request not functioning properly. It turns out that the sanctum.php configuration file was missing my local IP address (the one I am using to run my php artisan serve) in its 'stateful' array.

I share this in hopes that it may assist others facing a similar issue!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding a dynamic click event in HTML using IONIC 4

I've created a function using Regex to detect URL links and replace them with a span tag. The replacement process is working fine, but I'm facing an issue where when I include (click)="myFunction()" in the span, it doesn't recognize the cli ...

Troubleshooting the Hover Effect of Buttons in Next.js when Using Tailwind CSS for Dynamic Color Changes

Encountering a problem with button hover functionality in a Next.js component using Tailwind CSS. The objective is to alter the button's background color dynamically on hover based on a color value stored in the component's state. This code func ...

Issue: When attempting to read the length of a property in Angular 6, a TypeError is being thrown because the property is

Unable to retrieve values from an array using the TS code below: this.dataservice.get("common/public/getAllCategories", null).subscribe(data => { //console.log('categories'+JSON.stringify( data)); this.categoriesarray = data; }); var ...

Best approach to locate intersection in Laravel

In my Laravel application, I have User and Chat models. Users can be members of multiple chats, so I have set up a many-to-many relationship between the two using belongsToMany. Suppose I have several user IDs and I want to retrieve all common chats where ...

Searching for data across multiple tables using the Laravel framework combined with Vue.js and API integration

I am currently implementing a multi-search feature for a single table The search functionality is functioning correctly but only for one column Here is the snippet from my controller: public function index() { return Matter::when(request('sear ...

Determining the instance type of a TypeScript singleton class

I have a unique singleton implementation: class UniqueSingleton { private static instance: UniqueSingleton; private constructor() { // Only allows instantiation within the class } public static getInstance(): UniqueSingleton { if (!Unique ...

Using Angular and Typescript to Submit a Post Request

I am working on a basic Angular and Typescript page that consists of just one button and one text field. My goal is to send a POST request to a specific link containing the input from the text field. Here is my button HTML: <a class="button-size"> ...

Having difficulty transferring types to and from a custom module?

I'm currently faced with an issue while working on a typescript module within a larger monorepo. I am having difficulty importing types from one package into another via node modules. The types are located at ./types, and my package.json contains a ke ...

Modify the style of an element using a media query and Angular 4

Is there a way to update a class of an element based on the browser's width in my .ts file? matchMedia('(max-width: 400px)').addListener((mql => { if (mql.matches) { this.myclass = 'toggled'; } })); In the HTML, it shou ...

Angular: Streamlining the Constructor Function for Efficiency

Consider the scenario where we have these two components: export class HeroComponent { constructor( public service1: Service1, public service2: Service2, ) { // perform some action } } export class AdvancedHeroComponent extends HeroCompone ...

Refining a Form Collection in Angular

I have a list of cars that I am converting into a FormArray to display as buttons in an HTML list. My goal is to filter these cars based on their names. CarComponent.html <input #searchBox id="search-box" (input)="search(searchBox.value) ...

Need help setting up a time-based query in Laravel? Here's how to schedule it!

I am currently using the following query to update a status value. public function updateStatus(Request $request) { $customer = Customer::findOrFail($request->user_id); $customer->status = $request->status; $customer->new_customer_s ...

My issue lies in the subtraction of a quantity by using Object X from Array 1 and Object Y from Array 2

I am facing an issue with the function I'm using. It seems that when I attempt to do subtraction, both arrays are getting subtracted instead of just one. Here are the variables: let data1 = [ { ProductTotalId: 30, ProductId: 30, Quantity: 50 }, ...

What is the best way to save data from a Firebaselistobservable into an array?

I've been attempting to transfer data from Firebase to an array using Angular 2, but I'm facing difficulties in pushing the data into the array. Below is the code snippet: Variables: uid: string = ''; agencyItems: FirebaseListObserva ...

Issue: The login.component.html file failed to load

I attempted to utilize a custom-made HTML file with the templateUrl attribute in Angular2. Below is the content of my login.component.ts file: import {Component} from '@angular/core'; @Component({ selector: 'login' , template ...

What steps should I take to enable a clock plugin for my Discord Bot using the Discordeno framework?

I recently attempted to develop a plugin for a Discord bot utilizing the Discordeno Library. The goal of this plugin was to automatically update the name of a Voice channel to display the local time on the computer every minute. However, I encountered an i ...

Provide initial values to a custom TypeScript hook

As a new TypeScript user, I am trying to implement a hook called useForm to use in all forms. However, I am facing an issue with passing initial values using the code snippet below. Can someone help me troubleshoot this? interface IForm1 { name?: strin ...

What is the best way to transfer information from a child to its parent component?

In my child component, I have a variable containing the array result of a Barcode Scanner that I need to pass to the parent page. This array needs to be sent to an API. childComponent.ts this.consultList; parentComponent.ts export class ParentComponent i ...

The ngFor directive in Angular should be used with the Filter pipe to ensure that

Having a Filter implemented in my Angular Project that fetches data from Firebase. The current status in the Filter is as follows: Name 1: Lea Muster Name 2: Bruno Mustermann Name 3: Lea Muster Name 4: Gabriela Musterfrau The goal is to show duplicate e ...

Tips for incorporating Laravel packages into your project

My latest query is regarding Laravel, specifically the process of incorporating custom packages. I have successfully downloaded the package from this link: https://github.com/Riari/laravel-forum After following the provided instructions and registering t ...