Laravel REST API Interview Questions and Answers
In a Laravel REST API interview, you need to explain how you design HTTP endpoints and how you use Laravel’s tools to…
In a Laravel website, routes send each incoming request to the code that handles it, and Eloquent lets your PHP code work with database records as model objects. Together, they connect a URL such as /posts/5 to the post stored in your database.
A route matches a request by its HTTP method, such as GET or POST, and its URL path. Eloquent is Laravel’s object-relational mapper (ORM), a tool for querying and saving database records as model objects. In this guide, you’ll use routes and Eloquent to create a posts table, retrieve a post, and check data before saving it. These examples use Laravel 13, which requires PHP 8.3 or later, according to the Laravel release notes.
Laravel stores routes in the routes directory. If you are building pages and forms for a browser, put your routes in routes/web.php. Laravel applies web middleware to these routes, giving you session support and protection against cross-site request forgery (CSRF), an attack that tricks a user’s browser into sending an unwanted request. If you are building an API, use the API route file instead, where Laravel applies a different middleware group and commonly adds an /api prefix. See the routing documentation for the full list of route options.
A route combines an HTTP method, a URL path, and an action. For a small route, you can use a closure directly:
use Illuminate\Support\Facades\Route;
Route::get('/posts', function () {
return 'Posts';
});
As your code grows, move related request-handling methods into a controller, which is a PHP class whose methods handle incoming requests. For example, PostController::index handles requests for the list of posts, and PostController::show handles requests for a single post.
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
Route::get('/posts', [PostController::class, 'index'])
->name('posts.index');
Route::post('/posts', [PostController::class, 'store'])
->name('posts.store');
Route::get('/posts/{post}', [PostController::class, 'show'])
->name('posts.show');
The {post} segment is a route parameter. Laravel pulls the matching part of the URL and passes it to the route action. Route names such as posts.show give you a stable way to generate links and redirects without repeating the URL path across your codebase.
Eloquent models represent database records, and by convention Laravel maps a Post model to a table named posts. To create and update tables consistently, you use a migration, which is a versioned file that describes your database structure. Laravel’s migration documentation explains how these files define schema changes.
Generate a model and its migration together:
php artisan make:model Post -m
In the generated migration, define the fields the posts table needs:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('posts');
}
};
Run the migration to create the table:
php artisan migrate
The up method creates the table, and the down method describes how to undo that change. Calling timestamps() adds created_at and updated_at columns, which Eloquent uses to track when each record was created and last updated.
Eloquent gives you methods to find and update records. For example, Post::query()->latest()->get() fetches posts from newest to oldest, and Post::find(1) looks up a post by its primary key, the column that identifies it in the table. To update a record, assign a new value to a model attribute and call save().
Before you use create() to assign several attributes at once, tell Eloquent which fields it is allowed to accept. Laravel 13 supports a Fillable PHP attribute for this purpose:
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
#[Fillable(['title', 'body'])]
class Post extends Model
{
//
}
When your code passes an array of values to a model in one step, Laravel performs mass assignment. Listing allowed fields with Fillable stops an unexpected request field from overwriting a sensitive attribute on the model. The Eloquent documentation covers model conventions and mass-assignment protection. Because this attribute syntax depends on your Laravel version, check the documentation for your release if you use an older version.
With the model ready, a controller can list posts, display one post, and create a post from validated request data:
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController
{
public function index()
{
return Post::query()->latest()->get();
}
public function show(Post $post)
{
return $post;
}
public function store(Request $request)
{
$validated = $request->validate([
'title' => ['required', 'string', 'max:255'],
'body' => ['required', 'string'],
]);
$post = Post::create($validated);
return to_route('posts.show', $post);
}
}
Here, validate() checks the submitted title and body against your rules before the controller saves anything. Validation confirms that the input meets those rules, while mass-assignment protection limits which fields a bulk assignment can change. Laravel’s validation documentation explains how Laravel responds differently to standard web form submissions and XHR requests.
These controller methods return model data to keep the example short. In a browser application, you will usually return views for pages and redirects after form submissions, whereas in an API you should define the response format deliberately.
The show(Post $post) method uses implicit route model binding to look up a database record from a route parameter. Laravel matches the {post} parameter in the URL to the Post $post type declaration and fetches the matching record. If no post exists for that URL, Laravel returns a 404 response. For this convention to work, the route parameter name and the controller variable name have to match.
Route model binding only finds the record. Laravel does not check whether the current user has permission to view or change it, so you need to add authorization separately when posts have access restrictions. If you want URLs to use a field such as a slug instead of the post’s ID, you can also tell Laravel to bind by a chosen column, as described in the routing documentation.
A model relationship defines how database records connect, such as a post belonging to an author. You define this relationship on the Post model:
use App\Models\User;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
public function author(): BelongsTo
{
return $this->belongsTo(User::class);
}
By convention, Laravel expects the posts table to store the author’s ID in an author_id column. When a page needs both the posts and each post’s author, load them together with eager loading:
$posts = Post::with('author')->get();
If you skip eager loading and access each post’s author inside a loop, your code can run a separate database query for every post. In Laravel’s documented books-and-authors example, eager loading runs two queries: one for the books and one for their authors. The exact number of queries depends on the relationships and query you write. You can read more about eager loading and related options in the relationship documentation.
Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.
Take a look at vroni.com