How to build a mobile app backend with Laravel
Sep 02, 2025 am 08:34 AMUsing Laravel to build a mobile backend requires first installing the framework and configuring the database environment; 2. Define API routes in routes/api.php and return a JSON response using the resource controller; 3. Implement API authentication through Laravel Sanctum to generate tokens for mobile storage and authentication; 4. Verify file types when uploading files and store them on public disk, and create soft links for external access; 5. The production environment requires HTTPS, set current limits, configure CORS, perform API versioning and optimize error handling. It is also recommended to use API resources, paging, queues and API documentation tools to improve maintainability and performance. Use Laravel to build a secure, scalable mobile application backend.
Building a mobile app backend with Laravel is a solid choice because of its robust features, clean syntax, and built-in tools for authentication, routing, and database management. Laravel works well as a RESTful API backend for iOS, Android, or cross-platform apps. Here's how to set it up properly.
1. Set Up Laravel and Configure for API Use
Start by installing Laravel using Composer:
composer create-project laravel/laravel mobile-backend cd mobile-backend
Once installed, configure your .env
file with the correct database settings (eg, MySQL, PostgreSQL):
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=mobile_app DB_USERNAME=root DB_PASSWORD=
Laravel's default setup includes web routes, but for a mobile backend, you'll mostly use the API routes located in routes/api.php
. These are automatically prefixed with /api
and use stateless authentication.
2. Design API Endpoints and Use Resource Controllers
Define your API routes in routes/api.php
. For example, if you have a Post
model:
use App\Http\Controllers\PostController; Route::apiResource('posts', PostController::class);
Generate a resource controller:
php artisan make:controller PostController --resource
In your controller, return JSON responses:
public function index() { $posts = Post::all(); return response()->json($posts); } public function store(Request $request) { $post = Post::create($request->validate([ 'title' => 'required|string|max:255', 'body' => 'required', ])); return response()->json($post, 201); }
Always return JSON and appropriate HTTP status codes for mobile clients to handle responses correctly.
3. Secure Your API with Sanctum for Authentication
For mobile app authentication, Laravel Sanctum is ideal. It issues API tokens that mobile apps can store and send with each request.
Install Sanctum:
composer requires laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate
Add the Sanctum
middleware in app/Http/Kernel.php
under the api
group:
'api' => [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ],
Use Sanctum in your User model:
use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens; }
Create login and register endpoints:
// routes/api.php Route::post('/register', [AuthController::class, 'register']); Route::post('/login', [AuthController::class, 'login']); Route::middleware('auth:sanctum')->post('/logout', [AuthController::class, 'logout']);
In your AuthController
:
public function login(Request $request) { $credentials = $request->validate([ 'email' => 'required|email', 'password' => 'required', ]); if (!Auth::attempt($credentials)) { return response()->json(['message' => 'Invalid credentials'], 401); } $user = Auth::user(); $token = $user->createToken('mobile-token')->plainTextToken; return response()->json(['token' => $token, 'user' => $user]); }
The mobile app stores this token and sends it in the Authorization
header:
Authorization: Bearer <token>
4. Handle File Uploads and Storage
Mobile apps often upload images or files. Laravel makes this easy:
public function uploadAvatar(Request $request) { $request->validate([ 'avatar' => 'required|image|max:2048', ]); if ($request->hasFile('avatar')) { $path = $request->file('avatar')->store('avatar', 'public'); $url = Storage::url($path); auth()->user()->update(['avatar' => $url]); return response()->json(['url' => $url]); } return response()->json(['error' => 'No file uploaded'], 400); }
Make sure to run:
php artisan storage:link
So that storage/app/public
files are accessible via the web.
5. Optimize and Prepare for Production
- Enable HTTPS : Mobile apps require secure connections. Use a valid SSL certificate.
- Rate Limiting : Protect your API with throttling in
api
middleware. - CORS : If your frontend and backend are separate, use
fruitcake/laravel-cors
or Laravel's built-in CORS settings. - API Versioning : Start with
api/v1/posts
to allow future changes. - Error Handling : Customize
App\Exceptions\Handler
to return JSON errors.
Bonus Tips
- Use API Resources (
php artisan make:resource PostResource
) to format responses cleanly. - Consider pagination for large datasets:
Post::paginate(10)
. - Use queues and Redis for heavy tasks (eg, sending emails, processing images).
- Document your API using Swagger (OpenAPI) or Scribe for Laravel.
That's it. With Laravel, you get a scalable, secure, and maintainedable backend for your mobile app. Focus on clean API design, stateless authentication, and consistent JSON responses — and you're on the right track.
The above is the detailed content of How to build a mobile app backend with Laravel. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Create models and migration: Use phpartisanmake:modelPost-m to generate models and migration files, define the table structure and run phpartisanmigrate; 2. Basic CRUD operations: use Post::all(), find(), create(), save() and delete() methods to query, create, update and delete data; 3. Use Eloquent association: define belongsTo and hasMany relationships in the model, and use the with() method to preload the associated data to avoid N 1 query problems; 4. Eloquent query: use query constructor to chain calls such as where

PolymorphicrelationshipsinLaravelallowamodellikeCommentorImagetobelongtomultiplemodelssuchasPost,Video,orUserusingasingleassociation.2.Thedatabaseschemarequires{relation}_idand{relation}_typecolumns,exemplifiedbycommentable_idandcommentable_typeinaco

Yes,youcancreateasocialnetworkwithLaravelbyfollowingthesesteps:1.SetupLaravelusingComposer,configurethe.envfile,enableauthenticationviaBreeze/Jetstream/Fortify,andrunmigrationsforusermanagement.2.Implementcorefeaturesincludinguserprofileswithavatarsa

Laravel's TaskScheduling system allows you to define and manage timing tasks through PHP, without manually editing the server crontab, you only need to add a cron task that is executed once a minute to the server: *cd/path-to-your-project&&phpartisanschedule:run>>/dev/null2>&1, and then all tasks are configured in the schedule method of the App\Console\Kernel class; 1. Defining tasks can use command, call or exec methods, such as $schedule-

Create language files: Create subdirectories for each language (such as en, es) in the resources/lang directory and add messages.php file, or use JSON file to store translation; 2. Set application language: read the request header Accept-Language through middleware or detect language through URL prefix, set the current language using app()->setLocale(), and register the middleware in Kernel.php; 3. Use translation functions: use __(), trans() or @lang in the view, and use __() that supports fallback; 4. Support parameters and plural: Use placeholders in translation strings such as: n

Using Laravel to build a mobile backend requires first installing the framework and configuring the database environment; 2. Define API routes in routes/api.php and return a JSON response using the resource controller; 3. Implement API authentication through LaravelSanctum to generate tokens for mobile storage and authentication; 4. Verify file type when uploading files and store it on public disk, and create soft links for external access; 5. The production environment requires HTTPS, set current limits, configure CORS, perform API version control and optimize error handling. It is also recommended to use API resources, paging, queues and API document tools to improve maintainability and performance. Use Laravel to build a safe,

LaravelusesMonologtologmessagesviatheLogfacade,withdefaultlogsstoredinstorage/logs/laravel.log.Configurechannelsinconfig/logging.phptocontroloutput;thedefaultstackchannelaggregatesmultiplehandlerslikesingle,whichwritestoafile.UseLog::info(),Log::warn

Ensure that there is a remember_token column in the user table. Laravel's default migration already includes this field. If not, it will be added through migration; 2. Add a check box with name remember in the login form to provide the "Remember Me" option; 3. Pass the remember parameter to the Auth::attempt() method during manual authentication to enable persistent login; 4. "Remember Me" lasts for 5 years by default, and can be customized through the remember_for configuration item in config/auth.php; 5. Laravel automatically invalidates remember_token when password changes or user deletes. It is recommended to use HTTPS to ensure security in the production environment; 6
