What you'll learn
In this part of the series, you'll learn about the following:
- What controllers are, and how to create and use them in Laravel
- Implementing CRUD functionalities
- Routing in Laravel
- Implementing search functionality
Controllers
A controller in Laravel is a class that is used to organize logic in your application. For example, all the logic related to your Post
model will be inside the PostController
, these include, but not limited to functionalities like, creating, updating, reading, deleting, and searching post data from the database.
Creating controllers and CRUD functionalities
The easiest way to create a controller in Laravel is by running the following command:
php artisan make:controller PostController resource
The above command will create a PostController
file inside /app/Http/Controllers
folder, the resource
flag will generate common resource methods inside the controller file, so the generated file contents will look like so:
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return IlluminateHttpResponse
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param IlluminateHttpRequest $request
* @param int $id
* @return IlluminateHttpResponse
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function destroy($id)
{
//
}
}
In this file you have the dependencies and boilerplate of all the functions you need to create, read, update and delete data from the post table (again, Artisan to the rescue!), but since I'm building an API, I will remove some of them so I'll have the following functions:
-
store
for creating a post -
index
for fetching all data from theposts
table -
show
for fetching a single post -
update
for updating a post -
destroy
for deleting a post
Now that Laravel has scaffolded those functions, all you need to do is to define them anyhow you like.
Create a post (store
) function
The store
function as the name suggests, will be responsible for storing a post to the database. Thanks to Laravel's simplicity, you can add a resource with a single line like so:
public function store(Request $request)
{
return Post::create($request >all());
}
The above code uses the create
method on the Post
model to add all the data that comes in through the request
object to the database.
Fetch all posts (index
) function
The index
function will return all the posts in the database. For the PostController
, your index
function should look like so:
public function index()
{
return Post::all();
}
The above code uses the all
method on the Post
model to fetch all the posts from the database.
Fetch a single post (show
) function
The show
function will return a single post from the database. For the PostController
, your show
function should look like so:
public function show($id)
{
return Post::find($id);
}
The above code uses the find
method with the $id
as parameter on the Post
model to fetch the post with that particular id
from the database.
Update a post (update
) function
The update
function will update a post in the database. For the PostController
, your update
function should look like so:
public function update(Request $request, $id)
{
$post = Post::find($id);
$post >update($request >all());
return $post;
}
The above code does the following:
- Declares a
$post
variable with the result of thefind
method using the$id
as a parameter. That will be the post with that particular$id
in the database. - Use the
update
method to update with all the data passed to therequest
object as a parameter to update that particular post. - Returns the updated post.
Delete a post (destroy
) function
The destroy
function will delete a post from the database. For the PostController
, your destroy
function should look like so:
public function destroy($id)
{
return Post::destroy($id);
}
The above code uses the destroy
method with the $id
as parameter on the Post
model to delete the post with that particular id
from the database. Now that you've seen how to create controllers and define the create, read, update, and delete functions, Next, I'll show you how to connect those functions to routes(URLs) that the client will use to access data from the application.
Next, I'll show you how to work with routing in Laravel.
Routing
Routing in web development is the process of pointing a particular route in your application to the code or functionality that handles the request.
You've seen a bit of routing in Laravel when you wrote your first Route::get(...
function in the first part, Now lets handle routing in our application. After all the store, index, update and destroy functions have been defined, now go to the api.php
file inside /routes
folder and add the following to the dependencies on top of the file:
use AppHttpControllersPostController;
Creating routes
To create a post, you need to connect the store
function to a route like so:
Route::post('/posts', [PostController::class, 'store']);
The above route connects the store
function to any POST
request that goes to the localhost:8000/api/posts
with the fields to create a post like so:
{
"author_id": "1",
"title": "How to use Laravel",
"body": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",
"likes": 0,
"draft": 0
}
- The purple box is the type of request you'll send for this route, which is a
POST
request. - The yellow box is the URL of the route
localhost:8000/api/posts
. - The red box is the data I sent to the server in
JSON
format (notice that I did not add the id, created_at and updated_at fields as those will be added automatically, you can omit thelikes
anddraft
columns too, and their default values will be populated inside the database). - The green box is the result you'll get after sending the request successfully this will be the data that was created in the database (remember the function returns the created resource)
Fetch all posts
To fetch all the posts in the database, you need to connect the index
function to a route like so:
Route::get('/posts', [PostController::class, 'index']);
The above route connects the index
function to any GET
request that goes to the localhost:8000/api/posts
route, which will then return all the posts in the database like so:
- The purple box is the type of request you'll send for this route which is a
GET
request. - The yellow box is the URL of the route (localhost:8000/api/posts).
- The green box is the result you'll get after sending the request successfully this will be all the posts in the database.
Fetch a single post
To fetch a single post, you need to connect the show
function to a route like so:
Route::get('/posts/{id}', [PostController::class, 'show']);
The above route connects the show
function to any GET
request that goes to the localhost:8000/api/posts/1
which will then return the post with the id
of 1 or any number you add to the end of the URL
like so:
- The purple box is the type of request you'll send for this route, which is a
GET
request. - The yellow box is the URL of the route
localhost:8000/api/posts/1
. - The green box is the result you'll get after sending the request successfully this will be the posts with
id
of 1 in the database.
Update a single post
To update a single post, you need to connect the update
function
to a route like so:
Route::put