Posted on: January 29, 2020 03:18 PM
Posted by: Renato
Categories: Variados
Views: 769
O Laravel Model Observers é um ótimo recurso. Observadores são usados para agrupar ouvintes de eventos para um modelo. Nomes de métodos de classes de observadores referem-se ao evento Eloquent que você deseja ouvir. Esses métodos recebem o modelo como seu único argumento. O Laravel não inclui um diretório padrão para observadores. Além disso, o comando artesanal para gerar observadores também não está disponível por padrão.
Vamos implementar Model Observers em um projeto laravel e entender através de um exemplo simples.
Começando o projeto
laravel new observables
Configure seu banco de dados e adicione as credenciais. envArquivo. Estaremos demonstrando observadores através de um exemplo simples de produto. Primeiro, crie um modelo, um controlador e uma migração do produto, executando o seguinte comando:
php artisan make:model Product -mc
Adicionamos os sinalizadores m e c no comando acima.
Eles também criarão migração e controlador para o modelo respectivamente.
Agora, atualize o esquema no arquivo de migração que criamos na etapa anterior.
Será nomeado
create_products_table.php.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/** * Run the migrations.
*
* @return void
*/
public function up()
{ Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->integer('price');
$table->integer('quantity');
$table->timestamps();
});
} |
php artisan migrate
|
1
2
|
Route::get('/product', 'ProductController@create');
Route::post('/product', 'ProductController@store');
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
<!doctype html><html lang="en">
<head> <meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Model Observer</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head><body> <div class="container" style="margin-top: 50px;">
<div class="row">
<div class="col-sm-10 offset-sm-1">
@if($message = session()->pull('message'))
<div class="alert alert-success">{{ $message }}</div>
@endif
<form method="post" action="/product">
{{ csrf_field() }}
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Product Name">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="description" class="form-control"
placeholder="Enter Product Description"></textarea>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="number" class="form-control" id="price" name="price" placeholder="Enter Product Price">
</div>
<div class="form-group">
<label for="quantity">Quantity</label>
<input type="number" class="form-control" id="quantity" name="quantity"
placeholder="Enter Product Quantity">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
</div>
</form>
@if(count($errors))
<ul class="alert alert-danger well">
@foreach($errors->all() as $error)
<li class="list-unstyled">{{ $error }}</li>
@endforeach
</ul>
@endif
</div>
</div>
@if(count($products))
<hr class="dl-horizontal">
<div class="row">
<div class="col-sm-10 offset-sm-1">
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Description</th>
<th scope="col">Quantity</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
@foreach($products as $product)
<tr>
<th scope="row">{{ $loop->iteration }}</th>
<td>{{ $product->name }}</td>
<td>{{ $product->description }}</td>
<td>{{ $product->quantity }}</td>
<td>{{ $product->price }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
@endif
</div>
</body></html> |
Donate to Site
Renato
Developer