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 ‘ 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 – To save time in the long run, let’s utilize Laravel’s capabilities of layout files. In this section, we will Before we begin, it is important to note that .blade.php files do not require a starting or end PHP tag. Step 1 Step 2 Now to create the partial layouts that hook into the master layout we created above. Step 3 Let’s test the layouts by utilizing them within the welcome view. welcome.blade.php file Welcome to my CRUD App. Now, let’s render the page again Navigate to http://localhost/ in your browser It should now look similar to the screenshot below – 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 Let’s go! First, we must make sure the .env file has the right parameters that will authenticate with the MySQL database. Step 1 .env file settings 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 Step 2 Step 3 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 Step 2 Step 4 Finally, we are nearly finished with the database set up, we need to now create a model for the Student. We can again, use Step 1 Adding this And that is it for this section! Now it’s time to move on to our Controllers and views! 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 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 Now, if you look at this entire file, you will see the controller has been bootstrapped with seven functions – 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. 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. The create function, similar to the index, is responsible for returning the create view for the student data. Update the function as below 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 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. 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. 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. 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. Let’s move on to the routing. 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. Step 2 This very helpful information shows exactly how our application is structured Now, all that is missing is our front end views, let’s go ahead and finish the app off! 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. The index view will consist of a range of buttons and a data table. Let’s get building. Step 1 Step 2 Step 3 Now, render the student index view and check it out – Navigate to localhost/students/ A quick explainer on the code 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 Step 2 The code explained 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 The code explained 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 The code explained 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 And we are done! Feel free to now play with the application, try creating a new student record, edit it and delete it, etc. 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. 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 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! 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. The post Laravel CRUD Demo With Resource Controller Tutorial appeared first on Code Wall.DocumentRoot "C:/xampp/htdocs/crudApp/public"
Configuring The Layouts
@include('layouts.partials.meta')
@include('layouts.partials.header')
@include
code that calls to the partials folder which will be the home of our smaller layouts that we build in step 2.@yield
operator which will allow us to inject content into the layout from our views.meta.blade.php file
header.blade.php file
footer.blade.php file
@extends('layouts.master')
@section('pageTitle', 'Home')
@section('content')
Hello, world!
The Data
Configuring our .env file
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=
Creating the database
php artisan make:command CreateMySQLDb
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]);
}
}
php artisan create:mysqlDb laraveldb
Creating & Running Migrations
php artisan make:migration create_students_table
up()
function to reflect the code in the below snippetuse 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');
}
}
php artisan migrate
Creating the Student Model
php artisan
for this task.php artisan make:model Student
/**
* Fillable fields
*
* @var array
*/
protected $fillable = [
'first_name',
'last_name',
'age',
'email'
];
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.Creating the StudentController
make:controller controllerName
, but what we can actually also do with this command, is extend it and apply the resource option.php artisan make:controller StudentController --resource
use App\Student;
which will give our code access to the Student modelindex()
create()
store()
show()
edit()
update()
destroy()
index() function
public function index()
{
$students = Student::all();
return view('students.index', compact('students','students'));
}
create() function
public function create()
{
return view('students.create');
}
store() function
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
public function show($id)
{
$student = Student::findOrFail($id);
return view('students.show', compact('student','student'));
}
edit() function
public function edit($id)
{
$student = Student::find($id);
return view('students.edit', compact('student','student'));
}
update() function
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
public function destroy($id)
{
$student = Student::findOrFail($id);
$student->delete();
return redirect()->route('students.index');
}
Creating The Routes
Route::resource('students', 'StudentController');
php artisan route:list
Views
Index view
@extends('layouts.master')
@section('pageTitle', 'Students Index')
@section('content')
Students
Create New
@endsectionFirst Name
Last Name
Age
Email
Actions
@foreach($students as $student)
@endforeach
{{$student->first_name}}
{{$student->last_name}}
{{$student->age}}
{{$student->email}}
$students
variableDELETE
method request so that the route responds correctly.Create View
composer require laravelcollective/html
@extends('layouts.master')
@section('pageTitle', 'Create A Student')
@section('content')
Create New Student
@if ($errors->any())
@foreach ($errors->all() as $error)
@if ($errors->any())
Show View
@extends('layouts.master')
@section('pageTitle', 'Students Details')
@section('content')
Student Details
Edit View
@extends('layouts.master')
@section('pageTitle', 'Edit Students Details')
@section('content')
Edit Student
@if ($errors->any())
@foreach ($errors->all() as $error)
Form::text
value parameter, which we pass in the actual value of the existing record instead of an empty value.Finalizing the navigation
Video Demonstration
Summary
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.Source Repository
This post first appeared on Code Wall - Web Development & Programming, please read the originial post: here