Categories
PHP

Laravel 7 CRUD Application | Laravel 7 Tutorial For Beginners

In this article, you’ll be using Laravel 7 for building a CRUD example application with a MySQL database and Bootstrap 4.

Introducing Database CRUD?

CRUD stands for Create, Read, Update and Delete which are operations needed in most data-driven apps that access and work with data from a database.

You just need to follow few steps and you will get basic crud stuff using controller, model, route, bootstrap 4, and blade. I am going to show you step by step from scratch so, I will better to understand if you are new in laravel.

Before jump into the Laravel7 crud application lets understand few terms:

A composer is a tool that includes all the dependencies and libraries.
It allows a user to create a project with respect to the mentioned framework (for example, those used in Laravel installation). Third-party libraries can be installed easily with help of the composer.

Artisan is a command line interface used in Laravel. It includes a set of commands which assists in building a web application.

Step 1- Install Laravel7

First of all we need to get a fresh Laravel7 version application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel laravelcrud

Step 2- Database Configuration

In second step, we will make database configuration for example database name, username, password etc for our crud application of laravel 7. So let’s open .env file and fill all details like as bellow:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE= database name (moviesdb) 
DB_USERNAME= database user name (root)
DB_PASSWORD= database password ('')

Step 3- Create Migration

we are going to create a crud application for movies. so we have to create migration for “movies” table using Laravel 7 php artisan command, so first fire bellow command:

php artisan make:migration create_movies_table --create=movies

After this command you will find one file in the following path “database/migrations” and you have to put the below code in your migration file to create a movies table.

<?php

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

class CreateMoviesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('movies', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('genre');
            $table->string('release_year');
            $table->string('poster');
            $table->timestamps();
        });
    }

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

Now you have to run this migration by following command:

php artisan migrate

Step 4- Add Resource Route

Here, we need to add resource route for product crud application. so open your “routes/web.php” file and add following route.

routes/web.php

Route::resource('movies','MoviesController');

Step 5- Add Controller and Model

In this step, now we should create a new controller as MoviesController. So run the bellow command and create a new controller. bellow controller for creating a resource controller.

php artisan make:controller MoviesController --resource --model=Movie

After executing the above command you will find a new file in this path “app/Http/Controllers/MoviesController.php“. This controller will create seven methods by default as the below methods:

  1. index()
  2. create()
  3. store()
  4. show()
  5. edit()
  6. update()
  7. destroy()

So, let’s copy below code and put on app/Http/Controllers/MoviesController.php file.

<?php

namespace App\Http\Controllers;

use App\Movie;
use Illuminate\Http\Request;

class MoviesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $movies = Movie::latest()->paginate(4);
        return view('movies.index', compact('movies'))->with('i', (request()->input('page', 1) - 1) * 4);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $genres = ['Action', 'Comedy', 'Biopic', 'Horror', 'Drama'];

        return view('movies.create', compact('genres'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate(['title' => 'required',
            'genre' => 'required',
            'poster' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $imageName = '';
        if ($request->poster) {
            $imageName = time() . '.' . $request->poster->extension();
            $request->poster->move(public_path('uploads'), $imageName);
        }

        $data = new Movie;
        $data->title = $request->title;
        $data->genre = $request->genre;
        $data->release_year = $request->release_year;
        $data->poster = $imageName;
        $data->save();
        return redirect()->route('movies.index')->with('success', 'Movie has been added successfully.');
    }

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

        return view('movies.show', compact('movie'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Movie  $movie
     * @return \Illuminate\Http\Response
     */
    public function edit(Movie $movie)
    {
        $genres = ['Action', 'Comedy', 'Biopic', 'Horror', 'Drama'];
        return view('movies.edit', compact('movie', 'genres'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Movie  $movie
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Movie $movie)
    {
        $request->validate([
            'title' => 'required',
            'genre' => 'required',
        ]);

        $imageName = '';
        if ($request->poster) {
            $imageName = time() . '.' . $request->poster->extension();
            $request->poster->move(public_path('uploads'), $imageName);
            $movie->poster = $imageName;
        }

        $movie->title = $request->title;
        $movie->genre = $request->genre;
        $movie->release_year = $request->release_year;
        $movie->update();
        return redirect()->route('movies.index')->with('success', 'Movie has been updated successfully.');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Movie  $movie
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $movie = Movie::findOrFail($id);
        $movie->delete();
        return redirect()->route('movies.index')->with('success', 'Movie has been deleted successfully.');
    }
}

you can find “app/Movie.php” and put bellow content in Movie.php file:

app/Movie.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Movie extends Model
{
    protected $fillable = ['title', 'genre', 'release_year', 'poster'];
}

Step 6- Add Blade Files

In the last step. In this step, we have to create just blade files. So mainly we have to create a layout file and then create a new folder “resources/views/movies” then create blade files of the crud app. So finally you have to create the following bellow blade file:

  1. layout.blade.php
  2. index.blade.php
  3. create.blade.php
  4. edit.blade.php
  5. show.blade.php

So let’s just create following file and put bellow code.

resources/views/movies/layout.blade.php




    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 7 - Crud Application</title>
    <link rel="stylesheet" href="{{ asset('css/style.css') }}">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">


<div class="container">
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <a class="navbar-brand" href="/movies">Movies</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="{{ route('movies.create') }}">Add New</a>
      </li>
    </ul>
  </div>
</nav>
@yield('content')
</div>


resources/views/movies/index.blade.php

@extends('movies.layout')
@section('content')
<div class="wrapperdiv">

@if($messge = Session::get('success'))
<div class="alert alert-success text-center">{{ $messge }}</div>
@endif

<table class="table">
  <thead>
    <tr>
      <th scope="col"></th>
      <th scope="col">Title</th>
      <th scope="col">Genre</th>
      <th scope="col">Release Year</th>
      <th scope="col"></th>
    </tr>
  </thead>
  @if($movies)
  <tbody>
      @foreach($movies as $movie)
    <tr>
      <td class="align-middle"><img src="{{ asset('uploads/'.$movie->poster ) }} " class="img-thumbnail" /></td>
      <td class="align-middle">{{ $movie->title }}</td>
      <td class="align-middle">{{ $movie->genre }}</td>
      <td class="align-middle">{{ $movie->release_year }}</td>
      <td class="align-middle">
        <form action="{{ route('movies.destroy', $movie->id) }}" method="post">
        <a href="{{ route('movies.show', $movie->id)}} " class="btn btn-info">Show</a>
        <a href="{{ route('movies.edit', $movie->id)}}" class="btn btn-primary">Edit</a>
        @csrf
        @method('DELETE')
        <button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure want to delete?')">Delete</button>
        </form>
      </td>

    </tr>
    @endforeach
  </tbody>
  @endif
</table>
<div class="d-flex">
    <div class="mx-auto">
        {!! $movies->links() !!}
    </div>
</div>
</div>
@endsection

resources/views/movies/create.blade.php

@extends('movies.layout') @section('content')
<div class="wrapperdiv">
    <div class="formcontainer">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2>Add New Movie</h2>
                </div>
            </div>
        </div>
        @if($errors->any())
        <div class="alert alert-danger">
        <strong>Oops! There were some problems with your input.</strong>
        <ul>
            @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
            @endforeach
        </ul>
        </div>
        @endif
        <form
            action="{{ route('movies.store') }}"
            method="POST"
            enctype="multipart/form-data"
        >
            @csrf
            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group row">
                        <label for="title" class="col-sm-2 col-form-control"
                            >Title</label
                        >
                        <div class="col-sm-10">
                            <input
                                type="text"
                                name="title"
                                id="title"
                                class="form-control"
                            />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="genre" class="col-sm-2 col-form-control"
                            >Genre</label
                        >
                        <div class="col-sm-10">
                            <select
                                name="genre"
                                id="genre"
                                class="form-control"
                            >
                                <option value="">Select Genre</option>
                                @if($genres)
                                @foreach($genres as $genre)
                                <option value="{{ $genre }}">{{ $genre }}</option>
                                @endforeach
                                @endif
                            </select>
                        </div>
                    </div>

                    <div class="form-group row">
                        <label
                            for="release_year"
                            class="col-sm-2 col-form-control"
                            >Release Year</label
                        >
                        <div class="col-sm-10">
                            <input
                                type="text"
                                name="release_year"
                                id="release_year"
                                class="form-control"
                            />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="poster" class="col-sm-2 col-form-control"
                            >Poster</label
                        >
                        <div class="col-sm-10">
                            <input
                                type="file"
                                name="poster"
                                id="poster"
                                class="form-control-file"
                            />
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-sm-2"></div>

                        <div class="col-sm-10">
                            <button
                                type="submit"
                                name="submit"
                                id="submit"
                                class="btn btn-primary"
                            >
                                SUBMIT
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
@endsection

resources/views/movies/edit.blade.php

@extends('movies.layout') @section('content')
<div class="wrapperdiv">
    <div class="formcontainer">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2>Edit Movie</h2>
                </div>
            </div>
        </div>
    @if($errors->any())
    <div class="alert alert-danger">
        <strong>Oops! There were some problems with your input.</strong>
        <ul>
            @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
    @endif

        <form
            action="{{ route('movies.update', $movie->id) }}"
            method="POST"
            enctype="multipart/form-data"
        >
            @csrf
            @method('PUT')
            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group row">
                        <label for="title" class="col-sm-2 col-form-control"
                            >Title</label
                        >
                        <div class="col-sm-10">
                            <input
                                type="text"
                                name="title"
                                id="title"
                                class="form-control"
                                value="{{ $movie->title}}"
                            />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="genre" class="col-sm-2 col-form-control"
                            >Genre</label
                        >
                        <div class="col-sm-10">
                            <select
                                name="genre"
                                id="genre"
                                class="form-control"
                            >
                                <option value="">Select Genre</option>
                                @if($genres)
                                @foreach($genres as $genre)
                                    @if($genre == $movie->genre)
                                        <option value="{{ $genre }}" selected >{{ $genre }}</option>
                                    @else
                                        <option value="{{ $genre }}">{{ $genre }}</option>
                                    @endif
                                @endforeach
                                @endif
                            </select>
                        </div>
                    </div>

                    <div class="form-group row">
                        <label
                            for="release_year"
                            class="col-sm-2 col-form-control"
                            >Release Year</label
                        >
                        <div class="col-sm-10">
                            <input
                                type="text"
                                name="release_year"
                                id="release_year"
                                class="form-control"
                                value="{{ $movie->release_year }}"
                            />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="poster" class="col-sm-2 col-form-control"
                            >Poster</label
                        >
                        <div class="col-sm-10">
                            <input
                                type="file"
                                name="poster"
                                id="poster"
                                class="form-control-file"
                            />
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-sm-2"></div>

                        <div class="col-sm-10">
                            <button
                                type="submit"
                                name="submit"
                                id="submit"
                                class="btn btn-primary"
                            >
                                SUBMIT
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
@endsection

resources/views/movies/show.blade.php


@extends('movies.layout')
@section('content')
<div class="wrapperdiv">
    @if($movie)
<div class="row pb-5">
    <div class="col-4"></div>
    <div class="col-4">
    <div class="card" style="width: 20rem;">
        <img src="{{ asset('uploads/'.$movie->poster ) }}" class="card-img-top">
        <div class="card-body">
        <h5 class="card-title">{{ $movie->title }}</h5>
        <p class="card-text">{{ $movie->genre }} | {{ $movie->release_year }}</p>
        </div>
        </div>
    </div>
    <div class="col-4"></div>
</div>
    @endif
</div>
@endsection

Now we are ready to run our crud application example with Laravel 7 so run the below command for a quick run:

php artisan serve

Now you can open the below URL on your browser:

http://localhost:8000/movies

You will see layout as like below:

List Page:

Add Page:

Edit Page:

Show Page:

One reply on “Laravel 7 CRUD Application | Laravel 7 Tutorial For Beginners”

Leave a Reply

Your email address will not be published. Required fields are marked *