read the latest expo v52 and laravel v12 documentation and create an app for frontend…
- User
read the latest expo v52 and laravel v12 documentation and create an app for frontend with authentication with laravel v12 api with sanctum backend, only logged in users can access the app, registration is not needed, the app code should be modern and latest with best structures and security
- Assistant
To create an app with Expo SDK 52 for the frontend and Laravel 12 with Sanctum for the backend, follow these steps. This guide assumes you have basic knowledge of React Native, Expo, and Laravel.
Step 1: Setup Laravel 12 Backend
Install Laravel 12
First, install Laravel 12 using Composer:
composer create-project --prefer-dist laravel/laravel project-nameInstall Sanctum
Install Laravel Sanctum for authentication:
composer require laravel/sanctumPublish the Sanctum migrations and config:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"Run the migrations:
php artisan migrateConfigure Sanctum
In
config/sanctum.php, ensure that thestatefuldomains are configured correctly for your SPA or mobile app:'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1')),Create API Routes
Create routes for authentication in
routes/api.php:use App\Http\Controllers\AuthController; Route::post('/login', [AuthController::class, 'login']); Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); });Create an
AuthControllerto handle login logic:namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use App\Models\User; class AuthController extends Controller { public function login(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(['error' => 'Unauthorized'], 401); } $token = $user->createToken('auth_token')->plainTextToken; return response()->json(['access_token' => $token]); } }Step 2: Setup Expo SDK 52 Frontend
Create a New Expo App
Create a new Expo app using the latest SDK:
npx create-expo-app@latest my-app cd my-appUpdate
app.jsonto enable the New Architecture:{ "expo": { "name": "my-app", "slug": "my-app", "version": "1.0.0", "orientation": "portrait", "icon": "./assets/icon.png", "userInterfaceStyle": "light", "splash": { "image": "./assets/splash.png", "resizeMode": "contain", "backgroundColor": "#ffffff" }, "updates": { "fallbackToCacheTimeout": 0 }, "assetBundlePatterns": [ "**/*" ], "ios": { "supportsTablet": true }, "android": { "adaptiveIcon": { "foregroundImage": "./assets/adaptive-icon.png", "backgroundColor": "#FFFFFF" } }, "newArchEnabled": true } }Install Required Packages
Install
axiosfor making HTTP requests:npm install axiosImplement Authentication
Create a service to handle authentication:
// services/auth.js import axios from 'axios'; const api = axios.create({ baseURL: 'https://your-laravel-api.com/api', }); const login = async (email, password) => { try { const response = await api.post('/login', { email, password }); return response.data.access_token; } catch (error) { console.error(error); return null; } }; const getUser = async (token) => { try { const response = await api.get('/user', { headers: { Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.error(error); return null; } }; export { login, getUser };Secure Storage
Use
expo-secure-storeto securely store the token:npx expo install expo-secure-storeCreate a utility to handle token storage:
// utils/tokenStorage.js import * as SecureStore from 'expo-secure-store'; const storeToken = async (token) => { await SecureStore.setItemAsync('authToken', token); }; const getToken = async () => { const token = await SecureStore.getItemAsync('authToken'); return token; }; const removeToken = async () => { await SecureStore.deleteItemAsync('authToken'); }; export { storeToken, getToken, removeToken };Implement Login Screen
Create a login screen that uses the authentication service:
// screens/LoginScreen.js import React, { useState } from 'react'; import { View, Text, TextInput, Button } from 'react-native'; import { login } from '../services/auth'; import { storeToken } from '../utils/tokenStorage'; import { useNavigation } from '@react-navigation/native'; const LoginScreen = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const navigation = useNavigation(); const handleLogin = async () => { const token = await login(email, password); if (token) { await storeToken(token); navigation.navigate('Home'); } else { alert('Invalid credentials'); } }; return ( <view> <text>Login</text> <textinput onchangetext="{setEmail}" placeholder="Email" value="{email}"></textinput> <textinput onchangetext="{setPassword}" placeholder="Password" securetextentry="" value="{password}"></textinput> <button onpress="{handleLogin}" title="Login"></button> </view> ); }; export default LoginScreen;Protect Routes
Use a context or a hook to protect routes by checking for the token:
// hooks/useAuth.js import { useState, useEffect } from 'react'; import { getToken } from '../utils/tokenStorage'; import { getUser } from '../services/auth'; const useAuth = () => { const [user, setUser] = useState(null); useEffect(() => { const fetchUser = async () => { const token = await getToken(); if (token) { const userData = await getUser(token); setUser(userData); } }; fetchUser(); }, []); return { user }; }; export default useAuth;Use this hook in your app to ensure only logged-in users can access certain screens:
// App.js import React from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import LoginScreen from './screens/LoginScreen'; import HomeScreen from './screens/HomeScreen'; import useAuth from './hooks/useAuth'; const Stack = createNativeStackNavigator(); const App = () => { const { user } = useAuth(); return ( <navigationcontainer> <stack.navigator> {!user ? ( <stack.screen component="{LoginScreen}" name="Login"></stack.screen> ) : ( <stack.screen component="{HomeScreen}" name="Home"></stack.screen> )} </stack.navigator> </navigationcontainer> ); }; export default App;This setup ensures that only logged-in users can access the app, and registration is not required as per your request. The code is structured to follow modern best practices and security guidelines.
- User
it should use the latest file-routing
- Assistant
To implement the latest file-based routing with Expo Router in your app, follow these steps. This guide assumes you have already set up your Laravel 12 backend with Sanctum for authentication and have a basic Expo app structure.
Step 1: Setup Expo Router
Ensure that Expo Router is installed and configured in your project. If you're using a new Expo project, it should be included by default. Otherwise, you can install it manually:
npx expo install expo-routerMake sure your
app.jsonincludes theexpo-routerplugin:{ "expo": { "plugins": ["expo-router"] } }Step 2: Implement File-Based Routing
Expo Router uses a file-based approach to determine routes. Any file in the
appdirectory becomes a route. For example,app/index.tsxmatches the/route.Create Routes
- Login Route: Create a login screen at
app/login/index.tsx.
// app/login/index.tsx import React, { useState } from 'react'; import { View, Text, TextInput, Button } from 'react-native'; import { Link } from 'expo-router'; import { login } from '../services/auth'; import { storeToken } from '../utils/tokenStorage'; import { useNavigation } from 'expo-router'; const LoginScreen = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const navigation = useNavigation(); const handleLogin = async () => { const token = await login(email, password); if (token) { await storeToken(token); navigation.push('/home'); } else { alert('Invalid credentials'); } }; return ( <view> <text>Login</text> <textinput =="" onchangetext="{(text)"> setEmail(text)} placeholder="Email" value={email} /> <textinput =="" onchangetext="{(text)"> setPassword(text)} placeholder="Password" secureTextEntry={true} value={password} /> <button onpress="{handleLogin}" title="Login"></button> <link href="/register"/>Register </textinput></textinput></view> ); }; export default LoginScreen;- Home Route: Create a home screen at
app/home/index.tsx. This will be accessible only after logging in.
// app/home/index.tsx import React from 'react'; import { View, Text } from 'react-native'; import { useAuth } from '../hooks/useAuth'; const HomeScreen = () => { const { user } = useAuth(); if (!user) { // Redirect to login if not authenticated return <text>Please login first</text>; } return ( <view> <text>Welcome, {user.name}</text> </view> ); }; export default HomeScreen;- Not Found Route: Create a not found screen at
app/+not-found.tsx.
// app/+not-found.tsx import { Link } from 'expo-router'; import { View, Text, StyleSheet } from 'react-native'; const NotFoundScreen = () => { return ( <view style="{styles.container}"> <text>Page not found</text> <link href="/"/>Go to home screen </view> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, }); export default NotFoundScreen;Step 3: Protect Routes
Use a hook like
useAuthto protect routes by checking for authentication tokens:// hooks/useAuth.js import { useState, useEffect } from 'react'; import { getToken } from '../utils/tokenStorage'; import { getUser } from '../services/auth'; const useAuth = () => { const [user, setUser] = useState(null); useEffect(() => { const fetchUser = async () => { const token = await getToken(); if (token) { const userData = await getUser(token); setUser(userData); } }; fetchUser(); }, []); return { user }; }; export default useAuth;This setup uses the latest file-based routing with Expo Router and ensures that only logged-in users can access certain screens by leveraging authentication with Laravel Sanctum.
- Login Route: Create a login screen at
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.