1 - Crie um projeto chamado projetoeloquent.
cd /opt/php-verao
cp -R projetobase projetoeloquent
2 - Crie um database no MySQL com o nome livraria.
mysql -u root -psenha
create database livraria;
3 - Altere o arquivo .env que fica na raiz do projeto para configurar a conexão com o banco de dados.
...
# configuração do banco de dados local
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=livraria
DB_USERNAME=root
DB_PASSWORD=senha
...
4 - Crie um projeto no Github chamado projetoeloquent.
5 - Acrescente o projetoeloquent ao Github. Execute os comandos a partir do diretório raiz do projeto.
git init
git add .
git commit -m "primeiro commit"
git remote add origin https://github.com/<USUARIO_GITHUB>/projetoeloquent.git
git push origin master
6 - Crie um model com o nome Editora. Crie também o arquivo de migration e o controller.
php artisan make:model Editora -mc
7 - Altere o arquivo de YYYY_MM_DD_create_editoras_table.php que fica no diretório /database/migrations.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEditorasTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('editoras', function (Blueprint $table) {
$table->increments('id');
+ // colunas adicionadas
+ $table->string('nome');
+ $table->string('email');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('editoras');
}
}
7.1 - Antes de executar o migrate, altere o arquivo AppServiceProvider.php que fica no diretório /app/providers/. Para mais informações sobre o motivo da alteração desta classe acesse: Index Lengths & MySQL / MariaDB
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
+ use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
+ Schema::defaultStringLength(191);
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
8 - Execute o comando migrate para criar a nossa tabela editoras.
php artisan migrate
9 - Verifique que a tabela editoras foi criada no banco de dados livraria.
mysql -u root -psenha
use livraria;
show tables;
desc editoras;
10 - Insira alguns registros na tabela editoras.
mysql -u root -psenha
use livraria;
INSERT INTO editoras (nome, email, created_at, updated_at) VALUES ('Manning', 'manning@email.com', NOW(), NOW());
INSERT INTO editoras (nome, email, created_at, updated_at) VALUES ('OReilly', 'oreilly@email.com', NOW(), NOW());
INSERT INTO editoras (nome, email, created_at, updated_at) VALUES ('Apress', 'apress@email.com', NOW(), NOW());
11 - Altere o arquivo /routes/web.php para contemplar a url /editoras.
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
+ // Rota para url '/editoras'
+ Route::get('/editoras', 'EditoraController@index');
12 - Altere o controller EditoraController que fica no diretório /app/Http/Controllers. Acrescente o método index para listar as editoras.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
+ use App\Editora;
class EditoraController extends Controller
{
//
+ public function index()
+ {
+
+ $editoras = Editora::all();
+
+ return view('editora.index', compact('editoras'));
+
+ }
}
13 - Crie uma pasta editora dentro do diretório /resources/views.
14 - Crie um arquivo chamado index.blade.php para listar as editoras. Este arquivo deve ser criado dentro do diretório /resources/views/editora.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Listagem das Editoras</title>
<link rel="stylesheet" type="text/css" href="/css/app.css" />
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Listagem de editoras</h1>
</div>
<div class="row">
<div class="col-md-6">
<div class="panel panel-primary">
<div class="panel-heading">Editoras</div>
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Nome</th>
<th>Email</th>
</tr>
</thead>
<tbody>
@foreach ($editoras as $editora)
<tr>
<td>
{{$editora->id}}
</td>
<td>
{{$editora->nome}}
</td>
<td>
{{$editora->email}}
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/js/app.js" >
</body>
</html>
Acesse http://localhost:8000/editoras
15 - Altere o arquivo /routes/web.php para adicionar a url /editoras/1, por exemplo.
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
// Rota para url '/editoras'
Route::get('/editoras', 'EditoraController@index');
+ // Rota para url 'editoras/1', por exemplo
+ Route::get('/editoras/{editora}', 'EditoraController@show');
16 - Crie o método show no controller EditoraController, que fica no diretório /app/Http/Controllers.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Editora;
class EditoraController extends Controller
{
//
public function index()
{
$editoras = Editora::all();
return view('editora.index', compact('editoras'));
}
+ public function show(Editora $editora)
+ {
+
+ return view('editora.show', compact('editora'));
+
+ }
}
17 - Crie um arquivo chamado show.blade.php dentro do diretório /resources/views.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Editora</title>
<link rel="stylesheet" type="text/css" href="/css/app.css" />
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Detalhes da editora</h1>
</div>
<div class="row">
<div class="col-md-6">
<div class="panel panel-primary">
<div class="panel-heading"><strong>Editora</strong></div>
<ul class="list-group">
<li class="list-group-item">{{ $editora->nome }}</li>
<li class="list-group-item">{{ $editora->email }}</li>
</ul>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/js/app.js" >
</body>
</html>
18 - Acrescente o link para página de detalhes da editora, alterando o arquivo index.blade.php que fica no diretório /resources/views/editora/.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Listagem das Editoras</title>
<link rel="stylesheet" type="text/css" href="/css/app.css" />
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Listagem de editoras</h1>
</div>
<div class="row">
<div class="col-md-6">
<div class="panel panel-primary">
<div class="panel-heading">Editoras</div>
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Nome</th>
<th>Email</th>
+ <th>#</th>
</tr>
</thead>
<tbody>
@foreach ($editoras as $editora)
<tr>
<td>
{{$editora->id}}
</td>
<td>
{{$editora->nome}}
</td>
<td>
{{$editora->email}}
</td>
+ <td>
+ <a href="/editoras/{{ $editora->id }}">Detalhes</a>
+ </td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/js/app.js" >
</body>
</html>
Acesse http://localhost:8000/editoras
19 - Verifique e envie as alterações para o Github.
git status
git add .
git commit -m "acrescentando listagem e detalhes da editora"
git push origin master
1 - Criar o modelo Livro juntamente com o controller e migration.
2 - Alterar o arquivo YYYY_MM_DD_create_livros_table que fica no diretório /databases/migrations. Alterar o migration para que a tabela livros contenha as seguintes colunas:
livros | |
---|---|
coluna | tipo |
id | int unsigned |
titulo | varchar(255) |
preco | decimal(5,2) |
editora_id | int unsigned |
created_at | timestamp |
updated_at | timestamp |
3 - Acrescente a relação entre Editora e Livro, alterando a classe Livro que fica no diretório /app.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Livro extends Model
{
//
+ public function editora()
+ {
+ return $this->belongsTo(Editora::class);
+ }
}
4 - Crie uma página para exibir a listagem dos livros quando o usuário acessar /livros. Lembre-se: Além da página de listagem de livros, devemos alterar o controller e o arquivo routes/web.php.
5 - Crie uma página para exibir os dados do livro quando o usuário acessar /livros/1, por exemplo. Conforme o exercício anterior, o controller deve ser alterado e o arquivo routes/web.php também.