Uma das coisas mais legais do Laravel são seus Models e sua capacidade incrível de várias possibilidades, filtros pré-definidos e outros conceitos para aprimorar aquilo que o Model deveria compreender.
Antes de continuarmos esse assuntos vamos lembrar o que significa MVC?
Model: O tema do nosso assunto de hoje, este representa os dados do aplicativo, sua estrutura, lógica e comportamento. Trata de regras de negócio, realiza operações em database e responde a consulta sobre seus dados, em suma encapsula a lógica de negócio e o acesso aos dados.
View: Interface do usuário UI.
Controller: Controlador ele intermedia a transição entre a view e os model. Recebe solicitações do usuário por meio de interface, processa essas solicitações, "geralmente com base na lógica de negócios definidas pelo modelo" e atualiza o model. Além disso atualiza as views com novos dados após a atualização do modelo.
Existem 3 possibilidade de scope no Laravel, vamos falar mais do local scope pois utilizaremos mais, mas vou elencar os outros scope pra você ficar ciente da existência deles e como eles funcionam.
Global Scope
Global Scope é um scope que pode ser compartilhado entre vários Models diferentes, por exemplo você tem uma regra temporal e faz uma comparação com created_at em vários models, pode criar um scope global. Além de que ele sempre é utilizado pelo model.
Para criá-lo você deve gerar um arquivo do tipo scope rodando o comando:
php artisan make:scope TemporalScope
Nele é necessário ter o método apply onde aplicará a regra do scope.
Para aplicar esse scope em um Model existente você deve sobreescrever o método booted e invocar o método addGlobalScope.
protected static function booted(): void
{
static::addGlobalScope(new TemporalScope);
}
Para entender melhor sobre global scope, veja o link abaixo com a documentação oficial, não é o ênfase do nosso tema de hoje.
https://laravel.com/docs/10.x/eloquent#query-scopes
Anonymous Global Scope
Equivalente ao Global Scope porém utilizando-se dos conceitos anônimos, declaração de função sem nome por exemplo.
protected static function booted(): void
{
static::addGlobalScope('ancient', function (Builder $builder) {
$builder->where('created_at', '<', now()->subYears(2000));
});
}
Removendo global scope da consulta
Bem simples basta utilizar o método withoutGlobalScope e o nome do global scope.
Exemplo:
User::withoutGlobalScope(TemporalScope::class)->get();
Local Scope
Permite a definição de um conjunto de regras comunitárias para a query que você facilmanete poderá reutilizar no seu código.
Scope sempre deve retornar void.
Vou explicar o porque vou utilizar e como vou utilizar usando meu projeto SBBlog de exemplo, caso ainda não conheça e queira, é um código aberto de blog que mantenho para qualquer um utilizar e construir seu próprio blog.
https://github.com/andmarruda/sbblog
Retomando o raciocínio, o Sbblog por definição vem com um usuário criado que permite você logar, porém ele não deve ser um usuário que deva ficar ativo pois apresentária um enorme risco de segurança ao sistema, uma enorme vulnerabilidade, então o sistema verifica se o usuário logado é o primeiro usuário, se for ele te redireciona para a rota de criação de um novo usuário e te prende nela, forçando você criar um novo usuário, com isso automáticamente ele desativa o primeiro usuário e após alguns segundos te desloga do sistema, forçando você logar com o seu usuário definitivo, inclusive essa parte de desativação estará constando aqui em nosso artigo, pois estarei explicando sobre eventos em Models no Laravel.
No model eu tenho uma constante que segue:
const FIRST_USER_EMAIL = 'admin@admin.com';
Onde o email checa se o usuário é o usuário pré-definido pelo sistema.
O scope vai ficar da seguinte forma:
public function scopeFirstUserLogged(Builder $query) : void
{
$query->where('email', self::FIRST_USER_EMAIL)
->where('id', auth()->check() ? auth()->user()->id : -1);
}
Esse método recebe por definição o Builder do laravel Illuminate\Database\Eloquent\Builder , mas você notará que nem precisará se preocupar com isso, pois isso acontece internamente pelo Laravel, e o legal que esse scope serve também para métodos que retornam hasMany, belongsTo, hasOne e por ae vai...
Mas e como eu utilizo isso?
Extremamente simples no meu caso basta fazer a pergunta certa ao sistema...
User::firstUserLogged()->count() > 0 //0 isn`t 1 yes is him
Aqui já expliqueio o conceito, pra que serve e como utilizar, seguindo esse raciocínio passarei pra falar sobre eventos em Models, pois assim que criar um novo usuário eu quero desativar o usuário inicial do sistema, lembrando que nesse caso ele deve servir exclusivamente para gerar o ambiente para criação de um usuário.
Vamos criar um evento para quando inserir um usuário desabilitarmos o usuário que vem por padrão por medidas de segurança para o blog, inicialmente pensei em adicionar um evento de maneira simples usando o boot diretamente no model, mas decidi que vou criar um evento mesmo o que vai me permitir falar um pouco mais sobre isso e mostrar mais coisas para vocês.
Vamos criar um evento no Laravel usando o artisan.
php artisan make:event DisableFirstUser
No meu caso o evento vai se chamar DisableFirstUser "desabilite o primeiro usuário".
Irá criar um arquivo no seguinte formato:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class DisableFirstUser
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
Vamos trabalhá-lo para que atenda nossas especificações.
Vamos adicionar o model User.
use App\Models\User;
Vamos remover o broadcastOn e no lugar vamos adicionar o seguinte:
/**
* Handle with the event
*
* @return void
*/
public function handle() : void
{
if(!auth()->check() || auth()->user()->email != User::FIRST_USER_EMAIL)
return;
User::firstUser()->delete();
}
Nosso evento está criado, mas queremos que ocorra toda vez que for inserido um novo usuário.
Adicionei o if para não estimular o banco de dados toda hora, por mais que o usuário já estando desabilitado o estímulo é mínimo, mas acredito que o if é mais rápido do que o banco de dados nesse aspecto de DML do PostgreSQL que é o SGDB que estou usando.
Vamos adicionar o evento ao Model e no final da explicação coloco ambos os códigos aqui completos para vocês entenderem.
protected static function boot()
{
parent::boot();
static::created(function () {
event(new DisableFirstUser());
});
}
A função boot prepara o ambiente do Model, mantendo as características do seu parent e adicionando a sua própria, no caso quando um novo registro for criado então vai executar o evento que fizemos aqui.
Event:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Models\User;
class DisableFirstUser
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{}
/**
* Handle with the event
*
* @return void
*/
public function handle() : void
{
if(!auth()->check() || auth()->user()->email != User::FIRST_USER_EMAIL)
return;
User::firstUser()->delete();
}
}
Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Builder;
use App\Events\DisableFirstUser;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, SoftDeletes;
/**
* First user email
* @var string
*/
const FIRST_USER_EMAIL = 'admin@admin.com';
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = ['name', 'email', 'password', 'language_id'];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected static function boot()
{
parent::boot();
static::created(function () {
event(new DisableFirstUser());
});
}
/**
* Get the preferred language parent
* @version 1.0.0
* @author Anderson Arruda < andmarruda@gmail.com >
* @param
* @return Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function language() : \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(\App\Models\Language::class);
}
/**
* Scope check if is the first user
* @version 1.0.0
* @author Anderson Arruda < andmarruda@gmail.com >
* @param Builder $query
* @return void
*/
public function scopeFirstUser(Builder $query) : void
{
$query->where('email', self::FIRST_USER_EMAIL);
}
/**
* Scope check if is the first user logged
* @version 1.0.0
* @author Anderson Arruda < andmarruda@gmail.com >
* @param Builder $query
* @return void
*/
public function scopeFirstUserLogged(Builder $query) : void
{
$query->where('email', self::FIRST_USER_EMAIL)
->where('id', auth()->check() ? auth()->user()->id : -1);
}
}
Retificação 19/11/2023 - 19h14
Faltou declarar esse evento nos services provider.
Para isso vamos abrir o arrquivo app/Providers/EventServiceProvider, na propriedade $listen vamos adicionar:
DisableFirstUser::class => [
DisableFirstUser::class,
],
Esse arquivo ficando da seguinte forma:
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use App\Events\DisableFirstUser;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
DisableFirstUser::class => [
DisableFirstUser::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
}
Fim da retificação
Creio que é isso pessoal se tiverem dúvidas ou perguntas fiquem a vontade, se preferirem podem me procurar pelo meu Linkedin também.
https://www.linkedin.com/in/anderson-a-sborg/
Pessoal o Model do Laravel tem inúmeras outras ferramentas como relacionamentos, hasMany, belongsTo, hasOne e inclusive tem um método que permite fazer polimorfismo, quero muito abordar esses temas num artigo futuro. Mas preciso abranger mais pessoas pra que realmente me empolgue e valha a pena fazer esses conteúdos que eu particularmente adoro.
Compartilhem com seus amigos, divulgem, perguntem, fomentem discussão saudável aqui nos comentários.
Nos vemos no próximo artigo... Até lá!
PerplexityKupitten
22/11/2025 22:59perplexity pro купить pyyplbot https://uniqueartworks.ru/perplexity-kupit.html
MetabolicFreedomten
25/11/2025 02:24Metabolic Freedom reveals why most diets fail and how to fix your metabolism once and for all. https://metabolicfreedom.top/ metabolic freedom book com
LasMujeresPDFten
07/12/2025 11:19El libro que cambió la terapia de pareja para siempre disponible gratis https://lasmujeresqueamandemasiadopdf.cyou/ las mujeres que aman demasiado libro completo
NightingalePDFten
11/12/2025 20:09Immerse yourself in a story of danger and romance. The Nightingale PDF is available for download. It is a gripping narrative that follows the lives of two women as they navigate the perils of war and love. https://thenightingalepdf.top/ how many pages is the nightingale
fourthwingpdften
16/12/2025 23:21Prepare for a story where no character is safe. The Fourth Wing PDF captures the ruthlessness of the dragon riders' world. Get your digital copy and brace yourself for a wild ride. https://fourthwingpdf.top/ The Fourth Wing Pdf Free
acourtofmistandfurten
17/12/2025 09:05Ready to return to Prythian? The A Court of Mist and Fury PDF is your return ticket. This digital sequel is better than you can imagine. Get the download and start the adventure. https://acourtofmistandfurypdf.top/ A Court Of Mist And Fury Pdf Free Download
ironflamepdften
18/12/2025 16:23Iron Flame ignites epic storytelling! Follow Violet Sorrengail through skies of danger, passion, and discovery. Dragon riders unite! Download the complete PDF gratis at ironflamepdf.top – your adventure starts here! https://ironflamepdf.top/ Iron Flame Release Date
youcanscreampdften
20/12/2025 13:03This prequel makes you scream, and you can start the PDF. It is a zero. The digital file is first. one and only. https://youcanscreampdf.top/ You Can Scream Read Online
anarchiveofromanceten
20/12/2025 18:15I love the visual aspect of PDF layouts. Some files in an archive of romance are beautifully typeset. I enjoy reading a PDF that looks like a real book page, adding a touch of class to the digital reading experience. https://anarchiveofromancepdf.top/ Read An Archive Of Romance Full Novel
alcotthallpdften
20/12/2025 21:03The Alcott Hall PDF is a gateway to understanding the past. This document is vital for history students. Download it today to explore the rich narrative of the estate through a well-presented digital file. https://alcotthallpdf.top/ Alcott Hall Pdf Full
itshouldhavebeenyoten
20/12/2025 22:05Immerse yourself in the pure joy of reading this digital book. The PDF of It Should Have Been You is joyful. It should have been you smiling as you read. Download the copy today and read. https://itshouldhavebeenyoupdf.top/ It Should Have Been You Pdf Download Free
youcanscreampdften
21/12/2025 01:00You can access a thriller that makes you scream. The PDF version is crisp and clear. It is designed for readers who demand quality. Don't settle for less; get the best digital edition available and enjoy the story as it was meant to be read. https://youcanscreampdf.top/ You Can Scream Ebook
anarchiveofromanceten
21/12/2025 02:30There is something special about a book that makes you cry. An emotional archive of romance is full of tear-jerkers. I keep a box of tissues nearby when I open a new PDF, knowing that the story is going to pull at my heartstrings. https://anarchiveofromancepdf.top/ An Archive Of Romance Ava Reid Epub
itshouldhavebeenyoten
21/12/2025 07:14Immerse yourself in the drama and excitement of this novel through its digital format. The PDF edition of It Should Have Been You is perfect for modern readers. It should have been you turning the digital pages. Get the file immediately and lose yourself in the story. https://itshouldhavebeenyoupdf.top/ It Should Have Been You Characters
alcotthallpdften
21/12/2025 07:30Get instant access to the Alcott Hall PDF and explore its detailed content. This file is perfect for quick reference or in-depth study. Our reliable download service ensures that you can obtain this important document without any hassle or delay. https://alcotthallpdf.top/ Alcott Hall Pdf Mirror
anatomyofanalibipdten
21/12/2025 11:47Find the Anatomy of an Alibi PDF and enjoy. This digital download is easy. read whenever. https://anatomyofanalibipdf.top/ Anatomy Of An Alibi First Chapter
youcanscreampdften
21/12/2025 12:52You can access a report that makes you scream. This PDF is a fact. It is a news. The digital format is now. time and date. https://youcanscreampdf.top/ You Can Scream Thriller Book Pdf
myhusbandswifepdften
21/12/2025 13:01Unlock a world of suspense with just one click. This narrative is packed with tension and emotion. If you are searching for the My Husband's Wife PDF, you are in for a treat. Download the book and experience the thrill of a life unraveling. https://myhusbandswifepdf.top/ My Husband's Wife Waterstones Pdf
anarchiveofromanceten
21/12/2025 13:31There is a unique atmosphere in gothic romance. A specialized archive of romance often features these moody tales. I love downloading a PDF of a gothic novel on a stormy night, enhancing the spooky and romantic vibe of the reading experience. https://anarchiveofromancepdf.top/ An Archive Of Romance Romance Novel Pdf
anarchiveofromanceten
22/12/2025 00:28I was looking for a specific trilogy for weeks before I found it online. A dedicated archive of romance finally had the complete series. Being able to download the entire set in PDF was a relief, and I spent the whole weekend binge-reading the dramatic conclusion to the saga. https://anarchiveofromancepdf.top/ An Archive Of Romance A Study In Drown