Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Laravel CRUD Demo With Resource Controller Tutorial

In this tutorial based article we will learn how to use Laravel with CRUD methods in resource controllers by building a fully functioning application. The tutorial is for anyone, for those with beginner through to expert experience with the framework. The guide will go through step by step from scratch, leaving no stone unturned with building your own CRUD application.

Contents

  • Prerequisites
  • Installing & Configuration of a fresh Laravel project
  • Configuring the layouts
    • meta layout
    • header layout
    • footer layout
  • The data
    • .env file configuration
    • Creating the database
    • Creating & running migrations
    • Creating the model
  • Creating the controller
    • Index function
    • Create function
    • Store function
    • Show function
    • Edit function
    • Update function
    • Destroy function
  • Adding the routes
  • Building the views
    • Index view
    • Create view
    • Show view
    • Edit view
  • Finishing the navigation
  • Finishing the navigation
  • Video demonstration
  • Summary
  • Github Repo

Prerequisites

There are a few prerequisites that must be in place if you want to follow this tutorial from beginning to end. Check out the following list and make sure they are present on your development system.

  • A webserver with PHP & MySQL installed. I’m using XAMPP
  • Composer installed – I wrote an article on how to install composer for complete beginners that you can work through before we start.
  • A code editor, of course!

Installing & Configuration of a fresh Laravel project

Let’s go ahead and use composer to download and install our brand-new fresh out the box Laravel project.

Step 1

Use your command-line tool of choice and navigate to your web-servers route directory. In my case, its C:/xampp/htdocs/

Run the following command and let Composer do its work.

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

Step 2

Next, we want to instruct apache to use the Laravel’s /public/ folder as the root of our project.

Locate the httpd.conf file of your web server and find the ‘DocumentRoot’ and ‘

DocumentRoot "C:/xampp/htdocs/crudApp/public"

This part will vary depending on your OS and how your web server is set up. Meaning, the path to the project may differ, and the location of the httpd.conf file may differ.

Step 3

Let’s try to browse the new app!

Navigate to http://localhost/ in your browser

You should now see the homepage of the newly created Laravel application. Check out mine below –

Fresh Laravel installation home page

Configuring The Layouts

To save time in the long run, let’s utilize Laravel’s capabilities of layout files.

In this section, we will

  • Create and configure a master layout file
  • Create a footer, header and meta partial layout file
  • Add Bootstrap to the application in both the footer and meta layout files
  • Add a generic Bootstrap navigation to our header layout file.

Before we begin, it is important to note that .blade.php files do not require a starting or end PHP tag.

Step 1

  1. Create a new folder within the crudApp/resources/views folder named layouts.
  2. Create a new file within the new layouts folder named master.blade.php
  3. Add the following code to the master.blade.php file



    @include('layouts.partials.meta')




@include('layouts.partials.header')

@yield('content')
@include('layouts.partials.footer') @yield('scripts')
  • You will notice the @include code that calls to the partials folder which will be the home of our smaller layouts that we build in step 2.
  • Also, notice the @yield operator which will allow us to inject content into the layout from our views.

Step 2 

Now to create the partial layouts that hook into the master layout we created above.

  1. Navigate to the crudApp/resources/views/layouts and create a new folder named partials
  2. Create three new files named
    1. meta.blade.php
    2. header.blade.php
    3. footer.blade.php
  3. Then, update the files with the following code snippets

meta.blade.php file

@yield('pageTitle') | MyCrudApp

Step 3

Let’s test the layouts by utilizing them within the welcome view.

  1. Update the entire code inside of resources/views/welcome.blade.php to look like the following snippet.

welcome.blade.php file

@extends('layouts.master')

@section('pageTitle', 'Home')

@section('content')
    

Hello, world!

Welcome to my CRUD App.

@endsection

Now, let’s render the page again

Navigate to http://localhost/ in your browser

It should now look similar to the screenshot below –

The Data

With any CRUD app, we are going to need to think about the data that is going to be stored in the application. For this demo application, we can use something simple to provide the utmost understanding of the principles behind the CRUD.

The data we will have on the application will be all about Students. A single table that will record data like Student id, first name, second name, age, and email address.

For this particular section, we are going to proceed through the following points

  • Create a new database
  • Connect Laravel to MySQL
  • Create our Students migrations
  • Execute the migrations
  • Create a Student model

Let’s go!

Configuring our .env file

First, we must make sure the .env file has the right parameters that will authenticate with the MySQL database.

Step 1

  1. Locate the .env file which you will find in the project’s root directory.
  2. Find the following code snippet, and update it with correct credentials. If you’ve used a fresh web server install with MySQL, the default id and password will be root and the password blank. If not, update with the credentials that you have set.

.env file settings

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Creating the database

Now we have set the environment variables, we can go ahead and create a new Database. We can utilize the power of PHP artisan here with Laravel commands.

Step 1

  1. Fire up the command line and navigate to the project’s root directory
  2. Run the following command – php artisan make:command CreateMySQLDb

Step 2

  1. In the code editor file explorer, locate the new command file which is named CreateMySQLDb.php within the following folder app/Console/Commands.
  2. Edit the contents to look like the following snippet and save it.
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CreateMySQLDb extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'create:mysqlDb {name?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new mysql database schema based on the database config file';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $schemaName = $this->argument('name') ?: config("database.connections.mysql.database");
        $charset = config("database.connections.mysql.charset",'utf8mb4');
        $collation = config("database.connections.mysql.collation",'utf8mb4_unicode_ci');

        config(["database.connections.mysql.database" => null]);

        $query = "CREATE DATABASE IF NOT EXISTS $schemaName CHARACTER SET $charset COLLATE $collation;";

        DB::statement($query);

        config(["database.connections.mysql.database" => $schemaName]);

    }
}

Step 3

  1. Go back to the console and execute the following command php artisan create:mysqlDb laraveldb
  2. Now you can go check out phpMyAdmin to see the newly created database ‘laraveldb’. We are set to start making our migrations.

Creating & Running Migrations

So, as mentioned earlier, we are going to create a table that holds data on Students, a Student Table. For this, we must first create the migration, make the relevant adjustments, and execute it. This, in turn, will build our Student Table in the database, allowing us to proceed to the next part which is to create a Student Model.

Step 1

  1. In the command line, navigate to the project root directory.
  2. Execute the following command – php artisan make:migration create_students_table
  3. You will see a ‘Created Migration’ response when it’s been created!

Step 2

  1. In your project root directory, find the database/migrations/ folder.
  2. Locate the student_create_table migration file, which is preceded by a timestamp which is of the time executed, it will look something like 2020_05_16_133459_create_students_table.php
  3. Update the up() function to reflect the code in the below snippet
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name'); // Add
            $table->string('last_name'); // Add
            $table->integer('age'); // Add
            $table->string('email'); // Add
            $table->timestamps();
        });
    }

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

Step 4

  1. Back to the command-line interface and run the following command – php artisan migrate
  2. The migrations will execute, creating the table in the database, you should see a similar response to the screenshot below. Feel free to check the database and view the table at this point too.

Creating the Student Model

Finally, we are nearly finished with the database set up, we need to now create a model for the Student. We can again, use php artisan for this task.

Step 1

  1. Go to the command-line at the project root directory as always and execute the following command php artisan make:model Student
  2. In the code editor, navigate to the app/ folder, and you should see there is a new file present, the Student.php model file
  3. Add the following code to the Student model class.
/**
     * Fillable fields
     *
     * @var array
     */
    protected $fillable = [
        'first_name',
        'last_name',
        'age',
        'email'
    ];

Adding this fillable array will ensure Laravel allows us to ‘mass assign’ a student record which in English means allows us to send an array of data to create a new record.

And that is it for this section!

Now it’s time to move on to our Controllers and views!

Creating the StudentController

The controller creation has been made an absolute breeze with the power of the artisan console. As you are probably now aware, artisan comes with many commands that can be used to speed up development. One of which is make:controller controllerName, but what we can actually also do with this command, is extend it and apply the resource option.

The resource option instructs artisan to create a resource controller instead of a plain controller template, which essentially is a controller that handles all of the CRUD functionality we need (Create, Read, Update, Delete). So, let’s get on and get our new controller built!

Step 1

  1. Open the command line and navigate to the project root directory
  2. Type and execute the following command php artisan make:controller StudentController --resource
  3. In the code editor, navigate to the app/Http/Controllers directory and open up the new StudentController.php file
  4. Add the following use statement after the last use statement use App\Student; which will give our code access to the Student model

Now, if you look at this entire file, you will see the controller has been bootstrapped with seven functions –

  • index()
  • create()
  • store()
  • show()
  • edit()
  • update()
  • destroy()

Currently, these functions have empty bodies that we need to develop to work fluently with the view’s HTTP requests.

Step 2

Let us now develop our seven functions with the relevant Code to carry out our CRUD requests. Go through each of the following functions, updating the code to reflect the snippets.

index() function

The index function is solely responsible for returning the student index view with every student record that exists in the database. Update the function to reflect the code below.

public function index()
    {
        $students = Student::all();
        return view('students.index', compact('students','students'));
    }

create() function

The create function, similar to the index, is responsible for returning the create view for the student data. Update the function as below

public function create()
    {
        return view('students.create');
    }

store() function

The function store is responsible for accepting a POST request, accepting data submitted from the Create view. The function will attempt to validate the data by making sure whatever is marked as required is present. The validator also validates specific fields to make sure they are numeric and are of an email address format too! After that, the function will add the record to the database. Update the function to reflect the snippet below

public function store(Request $request)
    {
        $this->validate($request, [
            'first_name' => 'required',
            'last_name' => 'required',
            'age' => 'required|numeric',
            'email' => 'required|email',
        ]);

        $input = $request->all();

        Student::create($input);

        return redirect()->route('students.index');
    }

show() function

This function is responsible for the ‘Read’ part of the CRUD. It accepts a single ID which is then used to attempt to find the record in the database that matches that ID. Then, if found, returns the record into the ‘Show’ view. Refactor the show function to reflect the snippet below.

public function show($id)
    {
        $student = Student::findOrFail($id);
        return view('students.show', compact('student','student'));
    }

edit() function

Now, the edit function takes a parameter of the record ID we want to update. With that, it queries the database and grabs the record and passes it back into the edit view, which we can populate a form with the data ready for updating.

public function edit($id)
    {
        $student = Student::find($id);
        
        return view('students.edit', compact('student','student'));
    }

update() function

The update function is somewhat similar to the create function, the only real difference is we are grabbing the original record by the ID first, then updating it. The same validation checks are carried out to make sure no erroneous data is submitted too. Refactor the update function to match the below snippet.

public function update(Request $request, $id)
    {

        $student = Student::findOrFail($id);

        $this->validate($request, [
            'first_name' => 'required',
            'last_name' => 'required',
            'age' => 'required|numeric',
            'email' => 'required|email',
        ]);

        $input = $request->all();

        $student->fill($input)->save();

        return redirect()->route('students.index');
    }

destroy() function

Lastly, our destroy function, which is another term for delete. The function accepts an ID as a parameter to find the record we want to delete and of course, deletes it. If the record cannot be found and therefore, fails, a 404 not found page will be returned to the user.

public function destroy($id)
    {
        $student = Student::findOrFail($id);

        $student->delete();
        
        return redirect()->route('students.index');
    }

Let’s move on to the routing.

Creating The Routes

None of the functions we have created are any use without defining a route for them.

For example

localhost/students/create

Won’t render the create function we just defined unless we do the following in the routes.php file.

Step 1

Here we use a really magical one line route statement, a ‘resourceful’ route. Which rather than defining multiple routes for each function, this shortcut does it for us.

  1. Locate the routes/web.php file
  2. Add the following snippet to the bottom of the file
Route::resource('students', 'StudentController');

Step 2

  1. To check the magic this command has created head back to the command line.
  2. Execute the following command php artisan route:list
  3. You will see all the routes created for the student’s controller in the console response, just like below

This very helpful information shows exactly how our application is structured

  • The type of methods for each URL, for example, POST, GET.
  • The name and path of the views.
  • The controllers the URL and view connected too.

Now, all that is missing is our front end views, let’s go ahead and finish the app off!

Views

First of all, we will create our main student index view which will essentially interconnect with all of the other views and routes we’ve created.

Index view

The index view will consist of a range of buttons and a data table. Let’s get building.

Step 1

  1. In the code editor, locate the resources/views folder
  2. Create a new folder named students
  3. In the new folder create a new file name index.blade.php

Step 2

  1. Add the following code to the view
@extends('layouts.master')

@section('pageTitle', 'Students Index')

@section('content')
    

Students

Create New
@foreach($students as $student) @endforeach
First Name Last Name Age Email Actions
{{$student->first_name}} {{$student->last_name}} {{$student->age}} {{$student->email}}
id)}}" class="btn btn-info m-1">Details id)}}" class="btn btn-primary m-1">Edit
@endsection

Step 3

Now, render the student index view and check it out –

Navigate to localhost/students/

A quick explainer on the code 

  • As we know, the index function of the student controller passes in a $students variable
  • We use a Create link utilizing the create route to allow users to go and create a new student.
  • We use the variable loop over and populate a data table.
  • Within the table, we use some action buttons which utilize our other routes such as edit and delete. We use the $students variable to populate theses routes with the ID parameter they need.
  • Note that the delete button has to be wrapped in a form to make sure it’s submitted with a DELETE method request so that the route responds correctly.
  • And, the table is combined with some bootstrap styling to make it look nice!

Create View

Before we go any further, we are going to install an exclusive Laravel package that helps build HTML & HTML forms with Laravel views. Let’s install it and then build the create view.

Step 1

  1. In the command line, navigate to the project root directory
  2. Run the following command to install Laravel Collective HTML helper composer require laravelcollective/html

Step 2

  1. Create a new file in the resources/views/students folder named create.blade.php
  2. Add the code from the snippet below
@extends('layouts.master')

@section('pageTitle', 'Create A Student')

@section('content')
    

Create New Student


@if ($errors->any())
    @foreach ($errors->all() as $error)
  • {{ $error }}
  • @endforeach
@endif {{ Form::open(['action' => 'StudentController@store']) }} {{Form::token()}}
{{Form::label('first_name', 'First Name')}} {{Form::text('first_name', '', ['class' => 'form-control'])}}
{{Form::label('last_name', 'Last Name')}} {{Form::text('last_name', '', ['class' => 'form-control'])}}
{{Form::label('age', 'Age')}} {{Form::number('age', '', ['class' => 'form-control'])}}
{{Form::label('email', 'E-Mail Address')}} {{Form::text('email', '', ['class' => 'form-control'])}}
{{Form::submit('Create!', ['class' => 'btn btn-primary'])}} {{ Form::close() }} @endsection

The code explained 

  • You will notice at the near beginning of the file there is a code block starting with @if ($errors->any())
  • This code block is responsible for displaying errors that are caught during the validation process within the controller. For example, if the first name was missing, this part of the code will display that it needs to be filled in!
  • The rest of the code is pretty much the new Laravel Collective HTML helper which is quite self-explanatory, but I’ve place comments in the important parts.

Show View

Next up is the show view which I like to call the details page, this will show the details of any record that we pass the ID in for. It’s a pretty simple one!

Step 1

  1. Create a new file in the resources/views/students folder named show.blade.php
  2. Add the code from the snippet below
@extends('layouts.master')

@section('pageTitle', 'Students Details')

@section('content')
    

Student Details


First Name
{{$student->first_name}}
Last Name
{{$student->last_name}}
Age
{{$student->age}}
Email
{{$student->email}}
id)}}" class="btn btn-primary m-1">Edit
@endsection

The code explained 

  • As we know, the show controller function requires an ID, so it can return a student record to the show view.
  • In the view we access the student data and place it in some basic HTML
  • Lastly, similar to the index view, we use the routes available to us and passing in the required parameters from the student data to allow us to edit, and delete.

Edit View

Lastly, we need an edit view, to allow the user to update an existing record. The edit view controller function relies on having an ID to query the database and find the existing record. With the record, it passes it to the view and we populate the form with the values to be edited.

Step 1

  1. Create a new file in the resources/views/students folder named edit.blade.php
  2. Add the code from the snippet below
@extends('layouts.master')

@section('pageTitle', 'Edit Students Details')

@section('content')

    

Edit Student


@if ($errors->any())
    @foreach ($errors->all() as $error)
  • {{ $error }}
  • @endforeach
@endif {{ Form::open(['action' => ['StudentController@update', $student->id], 'method' => 'put']) }} {{Form::token()}}
{{Form::label('first_name', 'First Name')}} {{Form::text('first_name', $student->first_name, ['class' => 'form-control'])}}
{{Form::label('last_name', 'Last Name')}} {{Form::text('last_name', $student->last_name, ['class' => 'form-control'])}}
{{Form::label('age', 'Age')}} {{Form::number('age', $student->age, ['class' => 'form-control'])}}
{{Form::label('email', 'E-Mail Address')}} {{Form::text('email', $student->email, ['class' => 'form-control'])}}
{{Form::submit('Update!', ['class' => 'btn btn-primary'])}} {{ Form::close() }} @endsection

The code explained

  • The code of this view is essentially identical to the create view with minor changes.
  • It has the same validation error display if necessary.
  • One of the minor changes is the utilization of the Form::text value parameter, which we pass in the actual value of the existing record instead of an empty value.
  • And of course, the submit buttons name of ‘Update!’
  • Comments have been placed in the important parts of the code again.

Now we have our controller, all of the views, and routes in place we should update the navigation menu. We can add the index of the student’s section with one of its CRUD operation routes too.

Step 1

  1. In the code editor, locate the folder resources/views/layouts/partials and open the header.blade.php file
  2. Refactor the code inside to reflect the snippet below

And we are done!

Feel free to now play with the application, try creating a new student record, edit it and delete it, etc.

Video Demonstration

What would this tutorial be without a demo of the real thing? I put together this screen recording so you can see exactly how the application looks and how it works.

Summary

With the experience gained with this tutorial, you now have the tools to build Laravel applications with infinite types of data and CRUD operations. The principles are pretty much all the same for each type of data you want to create, for example, Teachers.

This article really shows the power of php artisan, and although you don’t have to use it, it really speeds up development and has no room for typos! The commands used in this tutorial are by no means its only capabilities either, so it worth looking into what else it can do.

I hope this guide helped you understand the principles of CRUD, the basics of the Laravel framework, and the artisan command-line helper.

If you have any questions, feel free to leave them in the comments!

Source Repository

I’ve pushed the code that has been used with this entire tutorial to GitHub if you want to reference anything or similarly use the entire code base to be the start of any project.

  • LaravelStudentCRUDApp Repository

The post Laravel CRUD Demo With Resource Controller Tutorial appeared first on Code Wall.



This post first appeared on Code Wall - Web Development & Programming, please read the originial post: here

Share the post

Laravel CRUD Demo With Resource Controller Tutorial

×

Subscribe to Code Wall - Web Development & Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×