<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Thiago Maciel</title>
    <description>The latest articles on DEV Community by Thiago Maciel (@thiagomrvieira).</description>
    <link>https://dev.to/thiagomrvieira</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F871013%2Fb7027357-694c-4f30-a9a9-d08a72565cf4.png</url>
      <title>DEV Community: Thiago Maciel</title>
      <link>https://dev.to/thiagomrvieira</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/thiagomrvieira"/>
    <language>en</language>
    <item>
      <title>Guia de estilo de código</title>
      <dc:creator>Thiago Maciel</dc:creator>
      <pubDate>Thu, 08 Feb 2024 21:26:23 +0000</pubDate>
      <link>https://dev.to/thiagomrvieira/guia-de-estilo-de-codigo-37mk</link>
      <guid>https://dev.to/thiagomrvieira/guia-de-estilo-de-codigo-37mk</guid>
      <description>&lt;h2&gt;
  
  
  Introdução
&lt;/h2&gt;

&lt;p&gt;Este guia de estilo de código tem como objetivo estabelecer diretrizes para a escrita de código claro, legível e consistente nas aplicações desenvolvidas pelo time. Adotar práticas de estilo de código consistentes não só torna o código mais fácil de entender e manter, mas também promove a colaboração entre os desenvolvedores.&lt;/p&gt;

&lt;p&gt;Para garantir que este documento permaneça relevante e útil ao longo do tempo, incentivamos a contribuição contínua de melhorias e sugestões. À medida que as tecnologias utilizadas em nossos projetos evoluem e novas práticas de desenvolvimento são adotadas, este guia será atualizado para refletir essas mudanças. Portanto, encorajamos os desenvolvedores a compartilhar suas experiências e insights para aprimorar este documento e ajudar a comunidade a escrever código de qualidade.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;strong&gt;Laravel&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Ferramentas de lint&lt;/strong&gt;: Laravel Pint&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Boas práticas&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;INDENTAÇÃO&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Laravel&lt;/strong&gt;: quatro espaços é a convenção padrão&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
if ($condition) {
  // código indentado com dois espaços
}

// Utilizar
if ($condition) {
    // código indentado com quatro espaços
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Angular&lt;/strong&gt;: dois espaços é a convenção padrão&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
if ($condition) {
    // código indentado com quatro espaços
}

// Utilizar
if ($condition) {
  // código indentado com quatro espaços
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;ul&gt;
&lt;li&gt;QUEBRA DE LINHA&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Legibilidade vs. Densidade de Informação&lt;/strong&gt;: A quebra de linha em instruções longas ou arrays torna o código mais legível, facilitando a compreensão. Embora possa aumentar ligeiramente a densidade vertical do código, a melhoria na legibilidade geralmente supera essa preocupação.&lt;br&gt;
Quebre linhas de código longas para melhorar a legibilidade.&lt;/p&gt;

&lt;p&gt;Laravel:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
return Response::json(['key' =&amp;gt; 'value', 'another_key' =&amp;gt; 'another_value']);

// Utilizar
return Response::json([
    'key' =&amp;gt; 'value',
    'another_key' =&amp;gt; 'another_value',
]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
$flights = Flight::where(‘active’, 1)-&amp;gt;orderBy(‘name’)-&amp;gt;take(10)-&amp;gt;get();

// Utilizar
$flights = Flight::where(‘active’, 1)
    -&amp;gt;orderBy(‘name’)
    -&amp;gt;take(10)
    -&amp;gt;get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Angular:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
&amp;lt;div toggle #firstToggle="toggle" (toggle)="onToggle('first', $event)" [ngClass]="{ 'active': isActive }" [ngStyle]="{ 'color': isActive ? 'blue' : 'red' }" *ngIf="isVisible"&amp;gt;

// Utilizar
&amp;lt;div toggle 
  #firstToggle="toggle" 
  (toggle)="onToggle('first', $event)"
  [ngClass]="{ 'active': isActive }"
  [ngStyle]="{ 'color': isActive ? 'blue' : 'red' }"
  *ngIf="isVisible"
&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;ul&gt;
&lt;li&gt;CHAVES&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Consistência vs. Economia de Espaço&lt;/strong&gt;: Usar chaves mesmo em blocos de código com uma única instrução promove a consistência e clareza. Embora possa parecer redundante em casos simples, ajuda a evitar erros quando mais instruções são adicionadas ao bloco no futuro.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Métodos e Funções&lt;/strong&gt;: Inicie as chaves na linha seguinte após a declaração do método ou função.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
public function exemplo(){
    // código
}

// Utilizar
public function exemplo()
{
    // código
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Classes&lt;/strong&gt;: Inicie as chaves na mesma linha a seguir à declaração da classe.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
class Exemplo {
    // código
}

// Utilizar
class Exemplo 
{
    // código
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Estruturas de Controle&lt;/strong&gt; (if, else, for, foreach, while, switch, etc.): Inicie as chaves na mesma linha da declaração da estrutura de controle.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
if ($condition) 
{
    // código
} else 
{
    // código
}

// Utilizar
if ($condition) {
    // código
} else {
    // código
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;ul&gt;
&lt;li&gt;OPERADOR TERNÁRIO&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Clareza vs. Complexidade&lt;/strong&gt;: O operador ternário é útil para expressões simples e curtas, mas pode comprometer a clareza em expressões mais complexas ou quando aninhados. Use-o com moderação e opte por clareza sobre concisão quando a lógica se tornar obscura.&lt;/p&gt;

&lt;p&gt;Laravel:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
$result = ($status === 'ativo') 
    ? ($role === 'admin'
        ? 'Usuário ativo com papel de administrador' 
        : 'Usuário ativo comum') 
    : 'Usuário inativo';

// Utilizar
$message = ($status === 'ativo') 
    ? 'Usuário ativo' 
    : 'Usuário inativo';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Angular:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
result = (status === 'ativo') 
    ? (role === 'admin'
        ? 'Usuário ativo com papel de administrador' 
        : 'Usuário ativo comum') 
    : 'Usuário inativo';

// Utilizar
message = (status === 'ativo') 
    ? 'Usuário ativo' 
    : 'Usuário inativo';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;ul&gt;
&lt;li&gt;COMENTÁRIOS&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Compreensão vs. Poluição do Código&lt;/strong&gt;: O código deve ser claro o suficiente para dispensar comentários, portanto quando necessário fazer comentários, priorize comentar o porquê ao invés de o que o código faz.&lt;/p&gt;

&lt;p&gt;Comentário Ruim (Focando no "O Quê"):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Calcula o desconto do cliente com base no tipo de cliente e histórico de compras.
const discount = calculateDiscount(customerType, purchaseHistory);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Comentário Bom (Explicando a Decisão de Design):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Usando um array para armazenar os dados porque precisamos preservar a ordem dos itens.
const data = [item1, item2, item3];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;ul&gt;
&lt;li&gt;ANNOTATIONS (php)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Documentação Completa vs. Concisa&lt;/strong&gt;: Métodos públicos devem ser documentados com annotations para garantir informações importantes sobre como usar esses métodos, incluindo detalhes sobre seus parâmetros, tipo de retorno e possíveis exceções lançadas.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 * Envia um e-mail de confirmação para o usuário.
 *
 * @param User $user O usuário para o qual enviar o e-mail.
 * @return void
 */
public function sendConfirmationEmail(User $user)
{
    // lógica para enviar e-mail de confirmação
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;ul&gt;
&lt;li&gt;NOMENCLATURAS&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Métodos e Funções&lt;/strong&gt;:&lt;br&gt;
Use verbos no infinitivo para descrever a ação realizada pelo método ou função. Exemplo: &lt;code&gt;calcularTotal()&lt;/code&gt;, &lt;code&gt;salvarUsuario()&lt;/code&gt;.&lt;br&gt;
Escolha nomes descritivos que indiquem claramente a finalidade ou o resultado esperado da ação.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Classes&lt;/strong&gt;:&lt;br&gt;
Use substantivos ou frases nominais para nomear classes. Exemplo: &lt;code&gt;UsuarioController&lt;/code&gt;, &lt;code&gt;PedidoService&lt;/code&gt;.&lt;br&gt;
Utilize o padrão PascalCase para nomes de classes, ou seja, inicie cada palavra com letra maiúscula e sem espaços entre as palavras.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variáveis&lt;/strong&gt;:&lt;br&gt;
Use nomes significativos e descritivos para variáveis.&lt;br&gt;
Evite abreviações obscuras ou nomes pouco claros.&lt;br&gt;
Prefira camelCase para nomes de variáveis, ou seja, inicie com letra minúscula e inicie cada palavra subsequente com letra maiúscula.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
$a = $request-&amp;gt;someInput;
$nome_variavel = 'Valor da variável';

// Utilizar
$someInput = $request-&amp;gt;someInput;
$nomeVariavel = 'Valor da variável';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Constantes&lt;/strong&gt;:&lt;br&gt;
Constantes dentro de uma classe deve ser declarado com todas as letras maiúsculas separado por underlines para nomes compostos:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const EMPRESA = 'Senai';
const TIPO_PRODUTO = 'Curso';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  &lt;strong&gt;Angular&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;INDENTAÇÃO
&lt;strong&gt;Espaços em Branco vs. Tabs&lt;/strong&gt;: Na comunidade Angular, é comum utilizar dois espaços para indentação. Isso ajuda a manter a consistência e legibilidade do código em todo o projeto, facilitando a colaboração entre os desenvolvedores.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
if (condition) {
    // código indentado com quatro espaços
}

// Utilizar
if (condition) {
  // código indentado com dois espaços
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;ul&gt;
&lt;li&gt;QUEBRA DE LINHA&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Legibilidade vs. Densidade de Informação&lt;/strong&gt;: quebrar linhas em instruções longas ou arrays melhora a legibilidade. Dividir o código em várias linhas torna cada parte mais clara e compreensível, facilitando a manutenção. Apesar de aumentar a densidade vertical, a legibilidade compensa, resultando em um código mais claro e fácil de entender&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Evitar
if (condition &amp;amp;&amp;amp; anotherCondition &amp;amp;&amp;amp; someOtherCondition &amp;amp;&amp;amp; lastCondition) {
  // Código executado se todas as condições forem verdadeiras
}

// Utilizar
if (condition
    &amp;amp;&amp;amp; anotherCondition
    &amp;amp;&amp;amp; someOtherCondition
    &amp;amp;&amp;amp; lastCondition
) {
  // Código executado se todas as condições forem verdadeiras
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Laravel — Your controllers should look like this</title>
      <dc:creator>Thiago Maciel</dc:creator>
      <pubDate>Fri, 30 Dec 2022 09:48:04 +0000</pubDate>
      <link>https://dev.to/thiagomrvieira/laravel-your-controllers-should-look-like-this-4ckn</link>
      <guid>https://dev.to/thiagomrvieira/laravel-your-controllers-should-look-like-this-4ckn</guid>
      <description>&lt;h2&gt;
  
  
  The scenario
&lt;/h2&gt;

&lt;p&gt;It’s not rare to start working on a project and need to deal with god classes controllers. Do you know what I mean? Who never faced a controller store method that validates, persists, creates a relation, sends emails, …, and return a response?&lt;/p&gt;

&lt;p&gt;I see it as a very common approach in the Laravel community, while the Rails devs tend to do almost the same in models classes. I don’t think it is that bad to have something else (in addition to handle the requests and responses) inside the controllers in some specific situations, but in general I would prefer to use the first principle of SOLID: Single-responsibility principle (SRP) doing a little more now to make it easier in the future.&lt;/p&gt;

&lt;p&gt;The benefits of moving business logic from controllers to new classes are countless, but let me mention three of them:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You’ll be able to reuse your code&lt;/li&gt;
&lt;li&gt;Your code will be easy to understand and maintain&lt;/li&gt;
&lt;li&gt;You’ll be the responsible for part of the next developer happiness 😊&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyte7krrbfkuu2rp6i45p.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyte7krrbfkuu2rp6i45p.gif" alt="funny developer" width="480" height="364"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Let’s see how to apply this concept refactoring a controller
&lt;/h2&gt;

&lt;p&gt;To make it simple let’s see an example where a UserController just validates the data, creates a new user, his roles and redirects with a status message:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function store(Request  $request)
{
  # Validate data
  $request-&amp;gt;validate([
    'name' =&amp;gt; 'required',
    'email' =&amp;gt; 'required|unique:users',
    'phone_number' =&amp;gt; 'required',
  ]);

  # Create a user
  $user = User::create([
      'name' =&amp;gt; $request-&amp;gt;name,
      'email' =&amp;gt; $request-&amp;gt;email,
      'phone_number' =&amp;gt; $request-&amp;gt;phone_number,
  ]);

  # Create the user's roles
  if(!empty($request-&amp;gt;roles)) {
    $user-&amp;gt;roles()-&amp;gt;sync($request-&amp;gt;roles);
  }

  #  Redirect with a status message
  return redirect()
    -&amp;gt;route('user.index')
    -&amp;gt;with('message','User created successfully.');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It looks fine, right? But we can make it better. First of all, lets move this validation to a Form Request by running this command:&lt;br&gt;
&lt;code&gt;php artisan make:request StoreUserRequest&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;It will create a new file in this directory: App\Http\Requests. I’ll just authorize the use and cut my validation rules from controller and paste it in the rules method like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
          'name' =&amp;gt; 'required',
          'email' =&amp;gt; 'required|unique:users',
          'phone_number' =&amp;gt; 'required',
        ];
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://laravel.com/docs/9.x/validation" rel="noopener noreferrer"&gt;How to use&lt;/a&gt; this class:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use App\Http\Requests\StoreUserRequest;


public function store(StoreUserRequest $request)
{
  # Create a user
  $user = User::create([
      'name' =&amp;gt; $request-&amp;gt;name,
      'email' =&amp;gt; $request-&amp;gt;email,
      'phone_number' =&amp;gt; $request-&amp;gt;phone_number,
  ]);

  # Create the user's roles
  if(!empty($request-&amp;gt;roles)) {
    $user-&amp;gt;roles()-&amp;gt;sync($request-&amp;gt;roles);
  }

  #  Redirect with a status message
  return redirect()
    -&amp;gt;route('user.index')
    -&amp;gt;with('message','User created successfully.');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A little better. Now we are going to create a new service class. This one will be the responsible for creating Users.&lt;/p&gt;

&lt;p&gt;Since we don’t have artisan commands to do it, we will need to create it manually. Inside the app directory I have created a service folder with my new class: app/Services/UserService.php and moved the logic from the controller to this class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
namespace App\Services;

use App\Models\User;
use Illuminate\Http\Request;

class UserService
{
    public function createUser(Request $request): User
    {
        # Create a user
        $user = User::create([
            'name' =&amp;gt; $request-&amp;gt;name,
            'email' =&amp;gt; $request-&amp;gt;email,
            'phone_number' =&amp;gt; $request-&amp;gt;phone_number,
        ]);

        # Create user's roles
        if(!empty($request-&amp;gt;roles)) {
          $user-&amp;gt;roles()-&amp;gt;sync($request-&amp;gt;roles);
        }
        return $user;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And now, in the controller, lets import and type-hint the dependency we just created:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use App\Services\UserService;

public function store(StoreUserRequest $request, UserService $userService)
{
    $userService-&amp;gt;createUser($request);

    return redirect()
      -&amp;gt;route('user.index')
      -&amp;gt;with('message','User created successfully.');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Could you notice the difference?&lt;br&gt;
Yeah, now we have more classes and files to work with, but in the other hand each one of them have it’s own responsibilities, they can be reused in other parts of the application and individually tested.&lt;/p&gt;

&lt;p&gt;Not to mention the controller that is now responsible only to receive the request, call the right service and return a response.&lt;/p&gt;

&lt;p&gt;Prettier, isn’t it?&lt;/p&gt;




&lt;h2&gt;
  
  
  Should I use service classes?
&lt;/h2&gt;

&lt;p&gt;Well it’s up to you to evaluate and decide what will work for your project. I personally prefer it, but I already have worked on projects where the approach was totally different.&lt;/p&gt;

&lt;p&gt;It is not a general rule, but when building a new application you should consider to keep each class as clean as possible including your controllers.&lt;/p&gt;

&lt;p&gt;Thank you for reading!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjgr96luyfdyr77ub29u0.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjgr96luyfdyr77ub29u0.gif" alt="thumbs up" width="162" height="162"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>angular</category>
      <category>typescript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Eloquent: API Resources</title>
      <dc:creator>Thiago Maciel</dc:creator>
      <pubDate>Fri, 19 Aug 2022 09:11:48 +0000</pubDate>
      <link>https://dev.to/thiagomrvieira/eloquent-api-resources-310</link>
      <guid>https://dev.to/thiagomrvieira/eloquent-api-resources-310</guid>
      <description>&lt;p&gt;&lt;strong&gt;What is API Resource in Laravel?&lt;/strong&gt;&lt;br&gt;
The best description comes from &lt;a href="https://laravel.com/docs/9.x/eloquent-resources"&gt;the official documentation&lt;/a&gt;:&lt;/p&gt;

&lt;p&gt;“it’s a (transformation) layer that sits between your Eloquent models and the JSON responses that are actually returned to your application’s users.”&lt;/p&gt;

&lt;p&gt;In other words, it is the class responsible for formatting the data that should be returned to the user as a response to a request.&lt;br&gt;
Instead of getting an instance of a model and manually set which field should be returned, you may use this layer.&lt;/p&gt;

&lt;p&gt;Removing this responsibility from your controller, model or other class, helps you to keep your code clean and easy to maintain.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Let’s see how it works&lt;/strong&gt;&lt;br&gt;
We’ll create some data just for testing purpose&lt;/p&gt;

&lt;p&gt;Since new Laravel projects comes with a default User model and migrations, let’s use this one. Let’s set the database connection and create some fake data.&lt;/p&gt;

&lt;p&gt;So create a new database, open your .env file and set the proper configuration there. My database config looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=api_resources
DB_USERNAME=root
DB_PASSWORD=
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let’s create some fake data for testing. In my DatabaseSeeder I just uncommented the user factory line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#database\seeders\DatabaseSeeder.php

&amp;lt;?php

namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        \App\Models\User::factory(10)-&amp;gt;create();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then I ran the migrate using the seed flag:&lt;br&gt;
&lt;code&gt;php artisan migrate --seed&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If you’re following these steps, I hope you have something like this 🤞:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rN8QOwID--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/swcwpj75saz8pwhutz23.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rN8QOwID--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/swcwpj75saz8pwhutz23.png" alt="migrations" width="699" height="204"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now I have the user’s table created and populated with these ten users we defined in the factory.&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;Creating and testing the endpoint&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now I just opened my api routes file, removed everything there and created a get route that returns the first instance of the User model.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#routes\api.php

&amp;lt;?php

use App\Models\User;
use Illuminate\Support\Facades\Route;

Route::get('/user', fn() =&amp;gt; User::first() );

/* Sure in real life the path would be the resource name in plural and you wont put this stuff in your routes file, I’m just trying to do the very basic here */
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So I ran the &lt;code&gt;php artisan server&lt;/code&gt; and hit the server:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gxPBfv0t--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rmen2viq1vo6qic0t4m4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gxPBfv0t--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rmen2viq1vo6qic0t4m4.png" alt="server running" width="700" height="83"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is what I received when I made a GET to 127.0.0.1:8000/api/user . It is my first instance of the User model.&lt;/p&gt;

&lt;p&gt;You should receive something different since the factory creates User entries randomly.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--YZshZJiy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/idjchi07efjfxaq1ytk9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YZshZJiy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/idjchi07efjfxaq1ytk9.png" alt="Get user model" width="700" height="167"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It works. Fine! My route returned the id, name, email, email_verified_at and timestamps fields. Those are the default User attributes.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;What if we wanted to return only specific fields?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;What should I do to return just the user &lt;code&gt;name&lt;/code&gt; and &lt;code&gt;email&lt;/code&gt; and 'hide' the other attributes?&lt;/p&gt;

&lt;p&gt;By default a model instance return all of it’s attributes, so if you need to show only specific ones you have a lot of ways to do it. One of them is setting what you want directly on the instance.&lt;/p&gt;

&lt;p&gt;Something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#routes\api.php

&amp;lt;?php

use App\Models\User;
use Illuminate\Support\Facades\Route;

Route::get('/user', fn() =&amp;gt; User::get(['name', 'email'])-&amp;gt;first() );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now it should return something like:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4fSgJOjC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fus49vbe8o695x4zsac5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4fSgJOjC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fus49vbe8o695x4zsac5.png" alt="get user" width="700" height="85"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Looks good, right? But…&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;What if the model had lot more attributes? Or what if I wanted to display some of user relations? What if depending on the user role, some field could be displayed, and some others couldn’t?&lt;/p&gt;

&lt;p&gt;There are a lot more “what if” that can make your code turn into a mess if you use this approach.&lt;/p&gt;

&lt;p&gt;So instead of setting each attribute directly in the route, controller or where else, you may use the Eloquent Api Resource.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Creating an Api Resource&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Assuming you’ve read &lt;a href="https://laravel.com/docs/9.x/eloquent-resources"&gt;the documentation&lt;/a&gt;, let’s create our transformation layer by running the following command:&lt;br&gt;
&lt;code&gt;php artisan make:resource UserResource&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;It will create a class called “UserResource” in this path app\Http\Resources. It should be something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bfIhKzJ8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t37km1fxli8da3istlbm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bfIhKzJ8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t37km1fxli8da3istlbm.png" alt="Api resource" width="700" height="274"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since we have a layer to set the fields that will be returned, we don’t need to do this in the route, so let’s get back to the route file and undo that get(['name', 'email']) and pass the instance of the user to this new layer (UserResource):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vcQU2ThT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/30kch7jwwm0a7anpe5hi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vcQU2ThT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/30kch7jwwm0a7anpe5hi.png" alt="routes" width="700" height="143"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And finally let’s set the attributes we want to show in the UserResource&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--usQsdacf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z4q1remfx2q2az5gtqoj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--usQsdacf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z4q1remfx2q2az5gtqoj.png" alt="userResource" width="700" height="143"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Notice that the changes in the UserResource file were:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Moving from:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return parent::toArray($request);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;To:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return [ 
  'name' =&amp;gt; $this-&amp;gt;name,
  'email' =&amp;gt; $this-&amp;gt;email,
];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;$this&lt;/strong&gt; represents the instance of the model retrieved and name and email are attributes of this model&lt;/p&gt;

&lt;p&gt;And the result is:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4hxZiATT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/habrsgsazzex1fgghy7k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4hxZiATT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/habrsgsazzex1fgghy7k.png" alt="Return" width="700" height="85"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---NUCNMhC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96gwzamz616j8kdr443z.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---NUCNMhC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96gwzamz616j8kdr443z.jpeg" alt="lazy dog" width="700" height="365"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I know, I know… it looks the same, but imagine the possibilities whenever you want to get a lot of different attributes, including attributes from related models.&lt;/p&gt;

&lt;p&gt;It was a very simple example, but trust me: it helps a lot when your project grows up and you want to keep the principle of the single responsibility.&lt;/p&gt;

&lt;p&gt;Your code will be cleaner and easy to understand.&lt;br&gt;
The next developer to get your code (and the future you) will be thank to your choice.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--GUMJb1lU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9beija9divlnwlk9visu.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--GUMJb1lU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9beija9divlnwlk9visu.gif" alt="thanks" width="480" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>eloquent</category>
      <category>api</category>
      <category>php</category>
    </item>
  </channel>
</rss>
