Skip to content

Instantly share code, notes, and snippets.

@mrezende
Last active January 29, 2018 21:49
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/5ec5490ef8343634162d1d06389d515a to your computer and use it in GitHub Desktop.
Save mrezende/5ec5490ef8343634162d1d06389d515a to your computer and use it in GitHub Desktop.

Exercícios de fixação

1 - Crie um projeto chamado controller.

cd /opt/php-verao
cp -R projetobase controller

2 - Crie um projeto no GitHub chamado controller.

3 - Adicione o projeto ao GitHub.

git init

git add .

git commit -m "primeiro commit"

git remote add origin https://github.com/<USUARIO_GITHUB>/controller.git

git push origin master

4- Crie um database chamado livraria_controller.

mysql -u root -psenha

create database livraria_controller;

quit

5 - Altere o arquivo .env da raiz do projeto.

APP_ENV=local
APP_KEY=base64:47UthkhOIQlLs7kup4BZA7/YVuPonaciQaJCap0GKDc=
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_controller
+ 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 os arquivo de migration e controller.

php artisan make:model Editora -mc

7 - Altere o arquivo de migration para acrescentar as colunas nome e email a Editora.

<?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 adicionar 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 - Adicione 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 editora dentro do diretório /resources/views.

14 - Crie um arquivo chamado index.blade.php dentro do 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" aria-hidden="true"></span> Editora
          </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

Acesse http://localhost:8000/editoras

15 - Acrescente a url /editoras/cria 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');

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 um arquivo chamado cria.blade.php dentro do diretório /resources/views/editora.

@extends('layouts.master')

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

@section('page-header-content', 'Cadastro da 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"></span> Editoras
          </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 name="nome" id="nome" type="text" class="form-control">
        </div>
        <div class="form-group">
          <label for="email">Email</label>
          <input name="email" id="email" type="text" class="form-control">
        </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 para permitir adição de vários campos ao mesmo tempo.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Acesse http://localhost:8000/editoras

21 - Envie as alterações ao GitHUb.

git add .

git commit -m "adicionando cadastro de editoras"

git push origin master

Exercícios complementares

1 - Altere o projeto para podermos editar as editoras.

2 - Acrescente ao projeto o cadastro de livros.

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 - Acrescente também a edição do livros.

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