https://assets.amuniversal.com/3dc1c10054b201394b85005056a9545dDilbert Daily Strip
Creating an API with Laravel in the proper way
https://dev.to/social_previews/article/638454.png
Starting with Laravel is easy and creating your first endpoint will take you just a few minutes. But, if you want to do it in the proper way to get a reusable, scalable and testable code you must read this before starting.
👉 Post disponible en español 🇪🇸
Before starting, just let you know that I had made a video talking about this with a step-by-step guide showing how to refactor your code without breaking anything and, this way, getting a more clean code. (In 🇪🇸 Spanish)
Ok! Let’s start with this post.
Usually, an endpoint in Laravel have three parts:
- The firs block of code in our controller is to validate the incoming request or getting some model from the URL.
- Next we do something with this data, for example, creating a user, sending an email, or whatever.
- Finally, we give to our API client a response in JSON.
This is a usual structure of an endpoint and a bad endpoint have all this part in the same controller file making all the code not reusable so, taking this into account, we are going to make our endpoint step-by-step.
TOC
Validate the request
In Laravel, we have a lot of different ways to use the validator class and check the entry data from the request but the best you can do, on a controller, it’s to use a custom request object.
You can create this by simply run artisan make:request UserStoreRequest
. This will create the file app/Http/Requests/UserStoreRequest.php
with a content similar to:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserStoreRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [];
}
}
As you can see, we have two main methods: one to check if the current user is authorized to perform this action or not.
You can use
Auth()
class here to get current user and check permissions if needed.
And the other method is used to pass validation rules to the request.
With that, you can use this class in your controller and the input data gets validated.
<?php
namespace App\Http\Controllers;
use App\Http\Request\UserStoreRequest;
class UserController extends Controller
{
/**
* Store a new user.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(UserStoreRequest $request)
{
$valid = $request->validated();
//
}
Creating application services
When all our input data is validated, and we have an expected and valid request we have to do something with that data.
A bad practice it’s to work with this data inside the controller. In our controller we have code that belongs to the infrastructure layer and this use cases must be in our application layer in order to make this code reusable and easy to test.
So, my recommendation it’s to create a service inside the folder app/Services
. Something like this:
<?php
declare(strict_types=1);
namespace App\Services;
use App\Mail\UserSignUpMail;
use App\Models\User;
final class UserStoreService
{
public function __invoke(
string $email,
string $name,
string $password
): User {
$password = \Hash::make($password);
return User::create([
'email' => $email,
'name' => $name,
'password' => $password
]);
}
}
As you can see, we are only hashing the password and creating the user in the invoke method. But, doing this in a service file instead of doing inside the controller allow us to write a simple unit test to check that the service it’s doing what we expect and also, we can reuse this code and calling it from another place, not only the controller.
For example, if we want to create a user from a Laravel Command we can use this same service and trigger the same use case without changing anything in our service code.
In our controller we just need to call this new service.
<?php
namespace App\Http\Controllers;
use App\Http\Request\UserStoreRequest;
class UserController extends Controller
{
private UserStoreService $storer;
public function __construct(UserStoreService $storer)
{
$this->storer = $storer;
}
/**
* Store a new user.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(UserStoreRequest $request)
{
$user = ($this->storer)(
$request->get('email'),
$request->get('name'),
$request->get('password')
);
}
Dispatching events
As you can see, our service it’s really simple, but in the real world that will never happen. Usually, when we create a user we must send an email, we need to create some configurations, send some notifications or whatever and that’s why we should use events and avoid overcomplicating our service.
If we use events we can listen to this event and trigger different actions in different parts of our code to keep each service and listener as simple as possible.
In Laravel, it’s really simple to trigger some events and listen to them and trigger some actions when needed.
The first thing we need it’s to create our event with artisan make:event UserCreated
. This event will receive the created user in the constructor.
Something like this:
<?php
namespace App\Events;
use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class UserCreated
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
}
And then, we create our listener to send a welcome email to the user after creating it. In our console we should run artisan make:listener SendWelcomeMail --event=UserCreated
and inside the handle
method we send our custom email.
And finally, you need to register the event in your User model in order to trigger it automatically every time a new user it’s created.
<?php
// ...
class User extends Authenticable
{
// ...
protected $dispatchesEvents = [
'created' => UserCreated::class,
];
}
Remember that you also need to register the event and the listner in your
EventServiceProvider
. You have more information inside Laravel documentation
Formatting the response
The last part of a good controller just need to get the result of the service we created before (if we are returning something) and transforming it in a valid JSON.
Usually, in Laravel, I found a lot of application that are just returning a model. This works, because Laravel can transform this models into a valid JSON but, if we have something else than a really simple API this it’s not a good idea.
The problem of doing this is that we are not customizing or defining anything and Laravel it’s returning our model with all fields all the time.
If you need more control, and you are going to need this sometime, you will need to create and return and API resource.
This API resources let you to customize the response by adding conditional fields but also relations, pagination and metadata.
This is the best you can do if you plan to create a good API full of services, endpoint and different kind of responses.
Laravel News Links
80 Laravel Interview Questions
https://res.cloudinary.com/practicaldev/image/fetch/s–rTABY4Xn–/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ncsx47qc7lsozzv2omj4.jpg
Hi everybody. If you’ve recently been invited to a Laravel interview, or you want to improve your skills about this framework, in 80 questions, we are going to discover more about Laravel. 😉
A Friendly Tip
These questions improve your general and technical knowledge about Laravel and prepare you for interviews. In this series we are going to explore something like Event/Listeners briefly. Knowing these items doesn’t guarantee that you will pass the interview! Passing the interview is hugely depends on how you are going to implement these items. For example you may be asked to make a program using Job/Queue.
Laravel has a lot of features and no one can claim that he/she knows everything about Laravel and is able to implement everything in the best way. Even it’s main developers!
So the best approach is to grasp basic knowledge about most Laravel features and be able to implement only some of these features in the best way. Companies aren’t looking for a person who knows everything. And the one who claims that he/she knows everything, will be likely rejected because of being overqualified which means he/she is good more that expectations.
So don’t worry if you don’t know everything. The thing is, you must know a few things like a hero 💪
Ok, let’s start.
What are we going to explore?
In this series we are going to answer these 80 questions:
Part 1:
- What do you know about Laravel?
- What are differences between Laravel and Lumen?
- Name a few important directories of the framework
- What does
bootstrap
directory do? - What is the usage of middleware?
- What is Artisan?
- What are differences between
has
andfilled
methods in theRequest
class? - What is ORM?
- What is Eloquent?
-
Name some important Laravel relationships
Part 2:
Will be added soon
Part 3:
Will be added soon
Part 4:
Will be added soon
Part 5:
Will be added soon
Part 6:
Will be added soon
Part 7:
Will be added soon
Part 8:
Will be added soon
Laravel News Links
Securely Copy Files in Linux With the Scp Command
There are times when you want to transfer files between your local system and a remote server. Several protocols and methods are available that allow you to handle file transmissions in a secure manner.
The scp command in Linux is one such tool that helps a user in sharing files remotely between local and remote hosts. In this article, we will discuss the scp command in detail, along with its usage and some additional features of the command.
What Is the Scp Command
Scp, an acronym for Secure Copy, is a command-line utility in Linux-based operating systems that allows a user to copy files between remote and local hosts. Since the command transfers files over a network to some other host, SSH access is required. SSH (Secure Shell) is a protocol that allows you to handle network services securely over any network.
The scp command also supports some additional features such as specifying authentication parameters, changing the port, transferring directories, and more.
Why Scp Is Better Than Other Methods
Scp is usually preferred over other file transfer methods because, during the transfer, the connection between the two hosts is encrypted. The SSH protocol is responsible for encrypting the files, passwords, and any other sensitive details.
Other transfer methods such as Telnet or FTP do not have any encryption. Also, the user/password keypair is also saved in plain text which is not a good practice at all. A cracker can easily access your information by sniffing your network.
How to Securely Transfer Files Using Scp
Using the scp command, you can transfer files between:
- A local host and a remote host
- A remote host and a local system
- Two remote hosts
Basic Syntax
The basic syntax of the scp command is:
scp [options] [source] [destination]
Transfer From Local Host to a Remote System
If you are a server administrator, then transferring files between a local host and remote hosts might be useful to you. To upload a file named document.txt to a remote host:
scp /home/document.txt user@remote-host:/home/document.txt
Note that the source is the path of the file on your local storage. And the destination is the path of the file on the remote host. You have to specify the username and domain name of the remote server as well. In the above command, user is the username and remote-host is the domain name.
The destination path is separated from the remote host details using the colon character (:). Keep in mind that the user must exist on the remote server if you want to transfer the files successfully. Also, the user should have write access to the directory in which you want to save the file.
After issuing the above-mentioned command, the system will ask you for the remote user’s password. Type the password and press Enter.
user@remote-host's password:
If the password is valid, the file transfer will initialize. If you entered an incorrect password, an error will occur.
Before trying to copy the file using the scp command, ensure that the remote host details and the password are correct by logging in to the server using SSH.
From a Remote Host to Local Host
To copy files from a remote host to a local host, just interchange the source and destination path in the scp command.
scp user@remote-host:/home/document.txt /home/document.txt
The system will ask you for the remote user’s password once again. Enter the password to confirm the transfer process.
Between Two Remote Hosts
To copy files between two remote servers, both the source and destination paths must be directories on the remote hosts.
scp user1@remote-host1:/home/document.txt user2@remote-host2:/home/folder/document.txt
Again, a prompt will appear asking you to enter the password for each of the two users.
Scp Command-Line Options
Apart from simply transferring the files from source to destination, scp has some additional options that can be invoked using specific arguments.
Change the Port
By default, the scp command works on port 22. However, you can always overwrite the default configuration and change the port. The -P flag allows you to do the same.
To use some other port number while copying files from a local host to a remote host:
scp -P 35 /home/document.txt user@remote-host:/home/document.txt
The aforementioned command will ensure that the scp command uses port 35 for transferring files.
Preserve File Timestamps
You might know that Linux sets timestamps for each file to store the modification time, access time, and change time associated with the file. When you transfer the file to another location using scp, the timestamps of the destination file are overridden by the current time.
If for any reason you want to preserve these timestamps, use the -p flag. Notice that -P and -p flags are different from each other.
scp -p /home/document.txt user@remote-host:/home/remote/document.txt
Copy Directories
If you want to copy directories instead of files, use the -r flag to transfer directories recursively.
scp -r user@remote-host:/home/videos /home/videos
Suppressed Mode
When you enter the scp command in order to transfer files, the terminal displays the progress bar and other related information on the screen. However, you can choose not to view this information using the -q flag.
scp -q user@remote-host:/home/document.txt /home/document.txt
Use a Keypair File for Authentication
If you want to authenticate the remote host connection using a keypair file, specify the path of the file using the -i flag.
scp -i /home/keypair.pem /home/document.txt user@remote-host:/home/document.txt
Chaining Multiple Flags Together
Just like any other Linux command, you can chain multiple arguments together to make the scp command more effective.
For example, to change the port and transfer files in suppressed mode:
scp -P 34 -q user@remote-host:/home/document.txt home/document.txt
If you want to use a keypair file for authentication and need to copy directories to the destination path:
scp -i /home/secret/keypair.pem -r /home/folder user@remote-host:/home/folder
File Transfer Between Linux Systems
In the world of the internet, transferring files between systems has become an essential task. For those who are administrating Linux servers, sometimes it is important to take a backup of the server before issuing a specific command. In situations like this, the scp command comes in handy.
Similarly, the cp command helps in copying the files from one location to another in a local system. There are many basic commands that are a must if you’re just getting started with Linux.
MUO – Feed
How Fishing Line Is Made
https://theawesomer.com/photos/2021/03/how_fishing_line_is_made_t.jpg
Some fishing lines are monofilament, while others are braided from multiple strands. Science Channel takes us inside a factory that produces braided line, combining numerous microfibers into a single strong one, then bathing them in dye for color. They show how they make a smooth line that’s been coated in resin.
The Awesomer