Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alxbbarbosa/347f26d5f8e9de08f4cbe0544701444a to your computer and use it in GitHub Desktop.
Save alxbbarbosa/347f26d5f8e9de08f4cbe0544701444a to your computer and use it in GitHub Desktop.
Artigo do Blog: Como construir rapidamente um CRUD utilizando Laravel - Controller Customers
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCustomersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name', 45);
$table->string('last_name', 45);
$table->text('address')->nullable();
$table->string('email')->nullable();
$table->string('phone')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('customers');
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>@yield('title')</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
@yield('content')
</body>
</html>
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = [
'first_name',
'last_name',
'address',
'email',
'phone',
];
}
<?php
use Faker\Generator as Faker;
$factory->define(App\Models\Customer::class, function (Faker $faker) {
return [
'first_name' => $faker->firstName,
'last_name' => $faker->lastName,
'email' => $faker->email,
'phone' => $faker->phoneNumber,
'address' => $faker->address
];
});
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CustomerRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'first_name' => 'required|max:45',
'last_name' => 'required|max:45',
];
}
public function messages()
{
return [
'first_name.required' => 'O campo nome é requerido',
'last_name.required' => 'O campo sobrenome é requerido',
'first_name.max' => 'O tamanho do nome inserido no campo não pode utltrapassar 45 caracteres',
'last_name.max' => 'O tamanho do nome inserido no campo não pode utltrapassar 45 caracteres',
];
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Customer;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use App\Http\Requests\CustomerRequest;
class CustomersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if ($request->has('search')) {
$search = $request->get('search');
$customers = Customer::where('first_name', 'like', "%{$search}%")
->orWhere('last_name', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%")
->orWhere('phone', 'like', "%{$search}%")
->orWhere('address', 'like', "%{$search}%")
->paginate(10);
$customers->appends(['search' => $search]);
return view('customers.grid', compact('customers', 'search'));
} else {
$customers = Customer::paginate(10);
return view('customers.grid', compact('customers'));
}
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('customers.form');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(CustomerRequest $request)
{
$customer = Customer::create($request->all());
if ($customer) {
Session::flash('success', "Registro #{$customer->id} salvo com êxito");
return redirect()->route('customers.index');
}
return redirect()->back()->withErrors(['error', "Registo não foi salvo."]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$customer = Customer::findOrFail($id);
if ($customer) {
return view('customers.form', compact('customer'));
} else {
return redirect()->back()->withErrors(['error', "Registo #{$id} não foi encontrado"]);
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(CustomerRequest $request, $id)
{
$customer = Customer::where('id', $id)->update($request->except('_token', '_method'));
if ($customer) {
Session::flash('success', "Registro #{$id} atualizado com êxito");
return redirect()->route('customers.index');
}
return redirect()->back()->withErrors(['error', "Registo #{$id} não foi encontrado"]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$customer = Customer::where('id', $id)->delete();
if ($customer) {
Session::flash('success', "Registro #{$id} excluído com êxito");
return redirect()->route('customers.index');
}
return redirect()->back()->withErrors(['error', "Registo #{$id} não pode ser excluído"]);
}
}
<?php
use Illuminate\Database\Seeder;
class CustomersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
factory(App\Models\Customer::class, 150)->create();
}
}
@extends('layout.app')
@section('title', 'Registro')
@section('content')
<h1>Registro</h1>
<hr>
<div class="container">
@include('layout.messages')
@if(isset($customer))
{!! Form::model($customer, ['method' => 'put', 'route' => ['customers.update', $customer->id ], 'class' => 'form-horizontal']) !!}
@else
{!! Form::open(['method' => 'post','route' => 'customers.store', 'class' => 'form-horizontal']) !!}
@endif
<div class="card">
<div class="card-header">
<span class="card-title">
@if (isset($customer))
Editando registro #{{ $customer->id }}
@else
Criando novo registro
@endif
</span>
</div>
<div class="card-body">
<div class="form-row form-group">
{!! Form::label('first_name', 'Nome', ['class' => 'col-form-label col-sm-2 text-right']) !!}
<div class="col-sm-4">
{!! Form::text('first_name', null, ['class' => 'form-control', 'placeholder'=>'Defina o nome']) !!}
</div>
</div>
<div class="form-row form-group">
{!! Form::label('last_name', 'Sobreome', ['class' => 'col-form-label col-sm-2 text-right']) !!}
<div class="col-sm-4">
{!! Form::text('last_name', null, ['class' => 'form-control', 'placeholder'=>'Defina o sobrenome']) !!}
</div>
</div>
<div class="form-row form-group">
{!! Form::label('email', 'E-mail', ['class' => 'col-form-label col-sm-2 text-right']) !!}
<div class="col-sm-8">
{!! Form::text('email', null, ['class' => 'form-control', 'placeholder'=>'Defina o email']) !!}
</div>
</div>
<div class="form-row form-group">
{!! Form::label('phone', 'Telefone', ['class' => 'col-form-label col-sm-2 text-right']) !!}
<div class="col-sm-4">
{!! Form::text('phone', null, ['class' => 'form-control', 'placeholder'=>'Defina o telefone']) !!}
</div>
</div>
<div class="form-row form-group">
{!! Form::label('address', 'Endereço', ['class' => 'col-form-label col-sm-2 text-right']) !!}
<div class="col-sm-10">
{!! Form::textarea('address', null, ['class' => 'form-control', 'placeholder'=>'Defina o endereço completo']) !!}
</div>
</div>
</div>
<div class="card-footer">
{!! Form::button('cancelar', ['class'=>'btn btn-danger btn-sm', 'onclick' =>'windo:history.go(-1);']); !!}
{!! Form::submit( isset($customer) ? 'atualizar' : 'criar', ['class'=>'btn btn-success btn-sm', 'style' =>'display:inline']) !!}
</div>
</div>
{!! Form::close() !!}
</div>
@endsection
@extends('layout.app')
@section('title', 'Listando todos os registros')
@section('content')
<h1>Listagem de Clientes</h1>
<hr>
{!! Form::open(['method' => 'get', 'route' => 'customers.index', 'class' => 'form-horizontal']) !!}
<div class="form-row form-group">
{!! Form::label('search', 'Procurar por', ['class' => 'col-sm-2 col-form-label text-right']) !!}
<div class="col-sm-8">
{!! Form::text('search', isset($search) ? $search : null, ['class' => 'form-control']) !!}
</div>
<div class="col-sm-2">
{!! Form::submit('procurar', ['class'=>'btn btn-primary']) !!}
</div>
</div>
{!! Form::close() !!}
<div class="container">
@include('layout.messages')
<table class="table table-bordered table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Nome</th>
<th>Sobrenome</th>
<th>email</th>
<th>telefone</th>
<th>
<a href="{{ route('customers.create') }}" class="btn btn-info btn-sm" >Novo</a>
</th>
</tr>
</thead>
<tbody>
@forelse($customers as $customer)
<tr>
<td>{{ $customer->id }}</td>
<td>{{ $customer->first_name }}</td>
<td>{{ $customer->last_name }}</td>
<td>{{ $customer->email }}</td>
<td>{{ $customer->phone }}</td>
<td>
<a href="{{ route('customers.edit', ['id' => $customer->id]) }}" class="btn btn-warning btn-sm">Editar</a>
<form method="POST" action="{{ route('customers.destroy', ['id' => $customer->id]) }}" style="display: inline"
onsubmit="return confirm('Deseja excluir este registro?');">
@csrf
<input type="hidden" name="_method" value="delete" >
<button class="btn btn-danger btn-sm">Excluir</button>
</form>
</td>
</tr>
@empty
<tr>
<td colspan="6">Nenhum registro encontrado para listar</td>
</tr>
@endforelse
</tbody>
</table>
{{ $customers->links() }}
</div>
@endsection
@if($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
</div>
@endif
@if(Session::has('info'))
<div class="alert alert-info">
{{ Session::get('info') }}
</div>
@endif
<?php
Route::get('/', function () {
return redirect()->route('customers.index');
});
//Route::get('customers/search', 'CustomersController@index')->name('customers.search');
Route::resource('customers', 'CustomersController');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment