Skip to content

Instantly share code, notes, and snippets.

@mrezende
Last active January 29, 2018 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrezende/fabfdb0d896899e3240768edab4c41c1 to your computer and use it in GitHub Desktop.
Save mrezende/fabfdb0d896899e3240768edab4c41c1 to your computer and use it in GitHub Desktop.

Exercícios de fixação

1 - Crie um projeto chamado validacao.

cd /opt/php-verao
cp -r projetobase validacao

2 - Crie um projeto no Github chamado validacao.

3 - Envie o projeto validacao para o Github.

git init

git add .

git commit -m "commit inicial"

git remote add origin https://github.com/mrezende/validacao.git

git push origin master

4 - Crie um database chamado livraria_validacao no MySQL.

mysql -u root -psenha

create database livraria_validacao;

5 - Altere as configurações do banco no arquivo .env.

APP_ENV=local
APP_KEY=base64:+f7Dd7ubXb1KIGRKugin0/iuOmVZBhOtglnwGyVAC48=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
+ DB_DATABASE=livraria_validacao
+ DB_USERNAME=root
+ DB_PASSWORD=senha

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

6 - Crie o modelo Editora junto com o arquivo de migration e controller.

php artisan make:model Editora -mc

7 - Altere o arquivo YYYY_MM_DD_create_editoras_table 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');

+            $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 tabela Editoras.

php artisan migrate

9 - Altere o arquivo routes/web.php para acrescentar 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');
});

+ Route::get('/editoras', 'EditoraController@index');

10 - Acrescente o método index na classe 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'));
+    }
}

11 - Crie uma pasta chamada layouts dentro do diretório /resources/views.

12 - Crie um arquivo chamado master.blade.php dentro do diretório /resources/views/layouts.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>@yield('title')</title>
    <link rel="stylesheet" href="/css/app.css" type="text/css" />
  </head>
  <body>

    <div class="container">

      <div class="page-header">
        <h1>@yield('page-header-content')</h1>
      </div>

      @yield('content')

    </div>

    <script src="/js/app.js" type="text/javascript"></script>
  </body>
</html>

13 - Crie uma pasta chamada editora dentro do diretório /resources/views.

14 - Crie um arquivo chamado index.blade.php no diretório /resources/views/editora.

@extends('layouts.master')

@section('title', 'Editoras')

@section('page-header-content', 'Editoras')

@section('content')

  <div class="row">
    <div class="col-md-3">
      <div class="panel panel-primary">
        <div class="panel-heading">
          <h3 class="panel-title">Ações</h3>
        </div>
        <div class="panel-body">
          <a href="/editoras/cria">
            <span class="glyphicon glyphicon-plus"></span> Editoras
          </a>
        </div>
      </div>
    </div>
    <div class="col-md-6">
      <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>

@endsection

15 - Altere o arquivo routes/web.php para contemplar a url /editoras/cria.

<?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');
});

Route::get('/editoras', 'EditoraController@index');

+ Route::get('/editoras/cria', 'EditoraController@cria');

16 - Acrescente o método cria na classe 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 cria()
+    {
+      return view('editora.cria');
+    }
}

17 - Crie a página cria.blade.php no diretório /resources/views/editora.

@extends('layouts.master')

@section('title', 'Cadastro de editora')

@section('page-header-content', 'Cadastro de editora')

@section('content')

  <div class="row">
    <div class="col-md-3">
      <div class="panel panel-primary">
        <div class="panel-heading">
          <h3 class="panel-title">Ações</h3>
        </div>
        <div class="panel-body">
          <a href="/editoras">
            <span class="glyphicon glyphicon-th-list"> Editoras</span>
          </a>
        </div>
      </div>
    </div>
    <div class="col-md-6">
      <form action="/editoras" method="POST">
        {{ csrf_field() }}
        <div class="form-group">
          <label for="nome">Nome</label>
          <input type="text" class="form-control" name="nome" id="nome" />
        </div>
        <div class="form-group">
          <label for="email">Email</label>
          <input type="text" class="form-control" name="email" id="email" />
        </div>
        <button class="btn btn-primary">Salvar</button>
      </form>
    </div>
  </div>

@endsection

18 - Acrescente a rota /editoras para requisições do tipo POST no arquivo /routes/web.php.

<?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');
});

Route::get('/editoras', 'EditoraController@index');

Route::get('/editoras/cria', 'EditoraController@cria');

+ Route::post('/editoras', 'EditoraController@armazena');

19 - Acrescente o método armazena na classe 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 cria()
    {
      return view('editora.cria');
    }

+    public function armazena()
+    {
+      Editora::create(request()->all());
+      return redirect('/editoras');
+    }
}

20 - Altere a classe Editora que fica no diretório app para aceitar a inserção de dados em massa.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Editora extends Model
{
    //
+    protected $fillable = [
+      'nome', 'email'
+    ];
}

Acesse http://localhost:8000/editoras.

21 - Tente cadastrar uma editora sem preencher o nome e email. Verifique que aparece uma mensagem de erro.

Acesse http://localhost:8000/editoras/cria

Cadastro de editora

Erro na submissão do formulário em branco

22 - Altere o método armazena para validar a obrigatoriedade do nome e email.

<?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 cria()
    {
      return view('editora.cria');
    }

    public function armazena()
    {
+      $this->validate(request(), [
+        'nome' => 'required|min:2|max:255',
+        'email' => 'required|email'
+      ]);
      Editora::create(request()->all());
      return redirect('/editoras');
    }
}

23 - Altere o arquivo cria.blade.php para exibir as mensagens de erro.

@extends('layouts.master')

@section('title', 'Cadastro de editora')

@section('page-header-content', 'Cadastro de editora')

@section('content')

  <div class="row">
    <div class="col-md-3">
      <div class="panel panel-primary">
        <div class="panel-heading">
          <h3 class="panel-title">Ações</h3>
        </div>
        <div class="panel-body">
          <a href="/editoras">
            <span class="glyphicon glyphicon-th-list"> Editoras</span>
          </a>
        </div>
      </div>
    </div>
    <div class="col-md-6">
+      @if(count($errors) > 0)
+        <div class="alert alert-danger">
+          <ul>
+            @foreach ($errors->all() as $message)
+              <li>{{ $message }}</li>
+            @endforeach
+          </ul>
+        </div>
+      @endif
      <form action="/editoras" method="POST">
        {{ csrf_field() }}
        <div class="form-group">
          <label for="nome">Nome</label>
          <input type="text" class="form-control" name="nome" id="nome" />
        </div>
        <div class="form-group">
          <label for="email">Email</label>
          <input type="text" class="form-control" name="email" id="email" />
        </div>
        <button class="btn btn-primary">Salvar</button>
      </form>


    </div>
  </div>

@endsection

Acesse http://localhost:8000/editoras/cria. Tente cadastrar uma editora com nome e email em brancos.

24 - Envie as alterações ao Github.

git add .

git commit -m "adicionando cadastro de editoras e validação"

git push origin master

Exercícios complementares

1 - Altere o projeto para editar as editoras. Acrescente a validação na edição.

2 - Crie um cadastro de livros. Acrescente a validação de obrigatoriedade dos campos.

Tabela Livros
coluna tipo
id integer unsigned
nome varchar(255)
preco decimal(5,2)
editora_id integer unsigned
created_at timestamp
updated_at timestamp

3 - Altere o projeto para editarmos os livros também. Acrescente a validação na edição.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment