Absolutely! Here’s a step-by-step guide to implementing login and registration in React Native with a Laravel backend using Sanctum for authentication.
1. Laravel Sanctum Setup (Backend)
Assumptions:
- You have a Laravel API project with Sanctum installed.
- CORS is configured to allow your React Native app.
Key Points:
- For mobile apps, use token-based authentication with Sanctum (
/sanctum/token), not cookie-based.
Example:
// routes/api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
Route::post('/register', function (Request $request) {
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$token = $user->createToken('mobile')->plainTextToken;
return response()->json(['token' => $token, 'user' => $user]);
});
Route::post('/login', function (Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
return response()->json(['message' => 'Invalid credentials'], 401);
}
$token = $user->createToken('mobile')->plainTextToken;
return response()->json(['token' => $token, 'user' => $user]);
});
// Protected route example
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
2. React Native Setup (Frontend)
Install Axios:
npm install axios
Example API URL:
const API_URL = 'http://your-laravel-api-url/api';
Registration Example
import axios from 'axios';
const API_URL = 'http://your-laravel-api-url/api';
export const register = async (name, email, password) => {
try {
const response = await axios.post(`${API_URL}/register`, {
name,
email,
password,
});
// Save token to AsyncStorage or context
return response.data;
} catch (error) {
throw error.response.data;
}
};
Login Example
import axios from 'axios';
const API_URL = 'http://your-laravel-api-url/api';
export const login = async (email, password) => {
try {
const response = await axios.post(`${API_URL}/login`, {
email,
password,
});
// Save token to AsyncStorage or context
return response.data;
} catch (error) {
throw error.response.data;
}
};
Usage in React Native Component
import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
import { login, register } from './api'; // The functions above
export default function AuthScreen() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [error, setError] = useState('');
const handleRegister = async () => {
try {
const data = await register(name, email, password);
// Save data.token to AsyncStorage
alert('Registered! Token: ' + data.token);
} catch (e) {
setError(e.message || 'Registration failed');
}
};
const handleLogin = async () => {
try {
const data = await login(email, password);
// Save data.token to AsyncStorage
alert('Logged in! Token: ' + data.token);
} catch (e) {
setError(e.message || 'Login failed');
}
};
return (
<View>
<TextInput placeholder="Name" onChangeText={setName} value={name} />
<TextInput placeholder="Email" onChangeText={setEmail} value={email} />
<TextInput placeholder="Password" secureTextEntry onChangeText={setPassword} value={password} />
<Button title="Register" onPress={handleRegister} />
<Button title="Login" onPress={handleLogin} />
{error ? <Text style={{color: 'red'}}>{error}</Text> : null}
</View>
);
}
Token Storage
Use AsyncStorage to store the token for authenticated requests.
npm install @react-native-async-storage/async-storage
Example:
import AsyncStorage from '@react-native-async-storage/async-storage';
// Save token
await AsyncStorage.setItem('token', data.token);
// Get token
const token = await AsyncStorage.getItem('token');
Authenticated Requests
const token = await AsyncStorage.getItem('token');
const response = await axios.get(`${API_URL}/user`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
Summary
- Use Laravel Sanctum’s token-based authentication for mobile.
- Register/Login endpoints return a token.
- Store the token in AsyncStorage.
- Send the token as a Bearer token in the Authorization header for protected routes.
If you need a full working example or have any issues, let me know!