CRUD

Route


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 redirect(route('alumni.index'));;
});

Route::resource('alumni', 'AlumniController');

$ php artisan route:list
+--------+-----------+------------------------+-----------------+------------------------------------------------+--------------+
| Domain | Method    | URI                    | Name            | Action                                         | Middleware   |
+--------+-----------+------------------------+-----------------+------------------------------------------------+--------------+
|        | GET|HEAD  | /                      |                 | Closure                                        | web          |
|        | GET|HEAD  | alumnus                | alumnus.index   | App\Http\Controllers\AlumnusController@index   | web          |
|        | POST      | alumnus                | alumnus.store   | App\Http\Controllers\AlumnusController@store   | web          |
|        | GET|HEAD  | alumnus/create         | alumnus.create  | App\Http\Controllers\AlumnusController@create  | web          |
|        | GET|HEAD  | alumnus/{alumnus}      | alumnus.show    | App\Http\Controllers\AlumnusController@show    | web          |
|        | PUT|PATCH | alumnus/{alumnus}      | alumnus.update  | App\Http\Controllers\AlumnusController@update  | web          |
|        | DELETE    | alumnus/{alumnus}      | alumnus.destroy | App\Http\Controllers\AlumnusController@destroy | web          |
|        | GET|HEAD  | alumnus/{alumnus}/edit | alumnus.edit    | App\Http\Controllers\AlumnusController@edit    | web          |
|        | GET|HEAD  | api/user               |                 | Closure                                        | api,auth:api |
+--------+-----------+------------------------+-----------------+------------------------------------------------+--------------+

Controller


$ php artisan make:controller AlumniController --resource --model=Alumnus

app/Http/Controllers/AlumniController.php

<?php

namespace App\Http\Controllers;

use App\Alumnus;
use Illuminate\Http\Request;

class AlumniController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $alumni = Alumnus::all();
        return view('alumni.index', compact('alumni'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('alumni.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email',
            'linkedin' => 'required|url',
        ]);
        // dd($validatedData);
        Alumnus::create($validatedData);

        return redirect(route('alumni.index'))->with('success', 'Alumnus is successfully saved');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Alumnus  $alumnus
     * @return \Illuminate\Http\Response
     */
    public function show(Alumnus $alumnus)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Alumnus  $alumnus
     * @return \Illuminate\Http\Response
     */
    public function edit(Alumnus $alumnus)
    {
        $alumnus = Alumnus::findOrFail($alumnus->id);
        return view('alumni.edit', compact('alumnus'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Alumnus  $alumnus
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Alumnus $alumnus)
    {
        $validatedData = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email',
            'linkedin' => 'required|url',
        ]);
        Alumnus::whereId($alumnus->id)->update($validatedData);

        return redirect(route('alumni.index'))->with('success', 'Alumnus is successfully saved');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Alumnus  $alumnus
     * @return \Illuminate\Http\Response
     */
    public function destroy(Alumnus $alumnus)
    {
        $alumnus = Alumnus::findOrFail($alumnus->id);
        $alumnus->delete();

        return redirect(route('alumni.index'))->with('success', 'Alumnus is successfully deleted');
    }
}

Model


app/Alumnus.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Alumnus extends Model
{
    protected $fillable = [
        'name',
        'email',
        'linkedin'
    ];
}

$ php artisan migrate
$ php artisan make:migration create_alumni_table
Created Migration: 2019_06_12_034853_create_alumni_table

Migration


database/migrations/2019_06_12_034853_create_alumni_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAlumniTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('alumni', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->string('linkedin');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('alumni');
    }
}

Seeder


$ php artisan make:seeder AlumniTableSeeder

database/seeds/AlumniTableSeeder.php

<?php

use App\Alumnus;
use Illuminate\Database\Seeder;

class AlumniTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $alumnus = new Alumnus;
        $alumnus->name = 'Luiz Chaves';
        $alumnus->email = 'luiz.chaves@ifpb.edu.br';
        $alumnus->linkedin = 'https://www.linkedin.com/in/luizcrchaves/';
        $alumnus->save();

        $alumnus = new Alumnus;
        $alumnus->name = 'Leandro Almeida';
        $alumnus->email = 'leandro.almeida@ifpb.edu.br';
        $alumnus->linkedin = 'https://www.linkedin.com/in/leandro-almeida-2601a611/';
        $alumnus->save();
    }
}

$ php artisan db:seed --class=AlumniTableSeeder

View


resources/views/layout.blade.php

<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <title>@yield('title')</title>
</head>

<body>
  <div class="container">
    <h1 class="text-center my-5">@yield('title')</h1>
    <div class="mt-4">
      @yield('content')
    </div>
  </div>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>

</html>

resources/views/alumni/index.blade.php


@extends('layout')

@section('title', 'Alumnus')

@section('content')
@if(session()->get('success'))
<div class="alert alert-success">
  {{ session()->get('success') }}
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div><br />
@endif
<table class="table table-striped">
  <thead>
    <tr>
      <td>ID</td>
      <td>Name</td>
      <td>Email</td>
      <td>Linkedin</td>
      <td colspan="2">Action</td>
    </tr>
  </thead>
  <tbody>
    @foreach($alumni as $alumni)
    <tr>
      <td>{{$alumni->id}}</td>
      <td>{{$alumni->name}}</td>
      <td>{{$alumni->email}}</td>
      <td>{{$alumni->linkedin}}</td>
      <td><a href="{{ route('alumni.edit', $alumni->id) }}" class="btn btn-primary" role="button">Edit</a></td>
      <td>
        <form action="{{ route('alumni.destroy', $alumni->id)}}" method="post">
          @csrf
          @method('DELETE')
          <button class="btn btn-danger" type="submit">Delete</button>
        </form>
      </td>
    </tr>
    @endforeach
  </tbody>
</table>
<a href="{{ route('alumni.create') }}" class="btn btn-primary" role="button">Add alumnus</a>
@endsection

resources/views/alumni/create.blade.php


@extends('layout')

@section('title', 'Create Alumnus')

@section('content')
<div class="card">
  <div class="card-header">
    Add Alumnus
  </div>
  <div class="card-body">
    @if ($errors->any())
    <div class="alert alert-danger">
      <ul>
        @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
        @endforeach
      </ul>
    </div>
    @endif
    <form method="post" action="{{ route('alumni.store') }}">
      <div class="form-group">
        @csrf
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name" name="name" />
      </div>
      <div class="form-group">
        <label for="email">Email:</label>
        <input type="text" class="form-control" id="email" name="email" />
      </div>
      <div class="form-group">
        <label for="linkedin">Linkedin:</label>
        <input type="text" class="form-control" id="linkedin" name="linkedin" />
      </div>
      <button type="submit" class="btn btn-primary">Create Alumnus</button>
    </form>
  </div>
</div>
@endsection

resources/views/alumni/edit.blade.php


@extends('layout')

@section('title', 'Edit Alumnus')

@section('content')
<div class="card">
  <div class="card-header">
    Edit Alumnus
  </div>
  <div class="card-body">
    @if ($errors->any())
    <div class="alert alert-danger">
      <ul>
        @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
        @endforeach
      </ul>
    </div>
    @endif
    <form method="post" action="{{ route('alumni.update', $alumnus) }}">
      <div class="form-group">
        @csrf
        @method('PATCH')
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name" name="name" value="{{ $alumnus->name }}" />
      </div>
      <div class="form-group">
        <label for="email">Email:</label>
        <input type="text" class="form-control" id="email" name="email" value="{{ $alumnus->email }}" />
      </div>
      <div class="form-group">
        <label for="linkedin">Linkedin:</label>
        <input type="text" class="form-control" id="linkedin" name="linkedin" value="{{ $alumnus->linkedin }}" />
      </div>
      <button type="submit" class="btn btn-primary">Update Alumnus</button>
    </form>
  </div>
</div>
@endsection

References