Welcome, Web Artisans, In today’s AppDividend Tutorial, I have shown the code of Laravel 5.4 Crud Example From Scratch. It is a simple Laravel 5.4 tutorial for beginners.
For creating Laravel Project, you need to have the following things.
- PHP >= 5.6.4
- OpenSSL PHP Extension
- PDO PHP Extension
- Mbstring PHP Extension
- Tokenizer PHP Extension
- XML PHP Extension
- Composer
Step 1: Create a Laravel project
Type the following command in your terminal to create a project.
composer create-project --prefer-dist laravel/laravel Laravel54
It will take 2 minutes to install a brand new Laravel Framework
After installing, go to your project root folder, and type php artisan serve in the terminal; your project URL might look like this
http://localhost:8000
Now open that laravel project folder in your favorite editor.
Step 2: Edit .env file for database configuration
In your project root folder, there is a file called .env, which we need to edit to set up a database configuration. I am using MySQL database.
// .env DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel54 DB_USERNAME=root DB_PASSWORD=mysql
Step 3: Use migrations provided by laravel to create users and password_resets table
Now go to the terminal, and run the following command
php artisan migrate
If you have created the database in MySQL and you have provided correct credentials to the .env file, then you will see there are three tables generated in the MySQL database.
Step 4: Create a controller file for our CRUD operations.
Go to the terminal, type the following command in your root project.
php artisan make:controller CRUDController --resource
Now go to laravel54 > app > Http > Controllers, you will see CRUDController file in that folder.
This file has all the boilerplate needed for our Crud operations.
Step 5: Create a model file for CRUD operations.
In the terminal, type the following command in your root project.
php artisan make:model Crud -m
This command will also create a migration file for our CRUD operations.
Step 6: Edit the crud migration file and create the required fields for the database.
Migration file is located in laravel54 > database > migrations folder.
<?php // create_cruds_table use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCrudsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('cruds', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->string('post'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('cruds'); } }
Run the following command in your terminal.
php artisan migrate
Step 7: Create views for set up a form
Go to laravel54 > resources > views . Locate into that folder and then create a master view called master.blade.php. A blade is templating engine used by laravel.
<!-- master.blade.php --> <!doctype html> <html lang="{{ config('app.locale') }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CRUD Operations</title> <!-- Fonts --> <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"> </head> <body> <br><br> @yield('content') </body> </html>
Now create a new folder inside the views directory called crud. Go inside that folder and create the following files
- index.blade.php
- create.blade.php
- edit.blade.php
Step 8: Create a form in create.blade.php
<!-- create.blade.php --> @extends('master') @section('content') <div class="container"> <form> <div class="form-group row"> <label for="lgFormGroupInput" class="col-sm-2 col-form-label col-form-label-lg">Title</label> <div class="col-sm-10"> <input type="text" class="form-control form-control-lg" id="lgFormGroupInput" placeholder="title" name="title"> </div> </div> <div class="form-group row"> <label for="smFormGroupInput" class="col-sm-2 col-form-label col-form-label-sm">Post</label> <div class="col-sm-10"> <textarea name="post" rows="8" cols="80"></textarea> </div> </div> <div class="form-group row"> <div class="col-md-2"></div> <input type="submit" class="btn btn-primary"> </div> </form> </div> @endsection
Step 9: Setup a route for the request handling.
Go to the routes > web.php
<?php Route::get('/', function () { return view('welcome'); }); Route::resource('crud', 'CRUDController');
Here we have added a resource route, and all the functions reside in app > Http > controllers > CRUDController.
Step 10: Edit CRUDController File
// CRUDController.php /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('crud.create'); }
Here we have to return the view when the request hits the route; it will be redirected to this controller’s create method. So our view should be accessible via the following URL the form.
http://localhost:8000/crud/create
We are now able to see the form with the two fields.
Step 11: Add CSRF token and set the post route of the form.
<!-- create.blade.php --> @extends('master') @section('content') <div class="container"> <form method="post" action="{{url('crud')}}"> <div class="form-group row"> {{csrf_field()}} <label for="lgFormGroupInput" class="col-sm-2 col-form-label col-form-label-lg">Title</label> <div class="col-sm-10"> <input type="text" class="form-control form-control-lg" id="lgFormGroupInput" placeholder="title" name="title"> </div> </div> <div class="form-group row"> <label for="smFormGroupInput" class="col-sm-2 col-form-label col-form-label-sm">Post</label> <div class="col-sm-10"> <textarea name="post" rows="8" cols="80"></textarea> </div> </div> <div class="form-group row"> <div class="col-md-2"></div> <input type="submit" class="btn btn-primary"> </div> </form> </div> @endsection
We have put the {{csrf_field()}} in the form so that malicious attacks can not harm our web application.
Step 12: Code the store function and use the Crud model to insert the data
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Crud; class CRUDController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('crud.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $crud = new Crud([ 'title' => $request->get('title'), 'post' => $request->get('post') ]); $crud->save(); return redirect('/crud'); } /** * 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) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
Here we need to create a protected field called $fillable in the Crud model. Otherwise, it will throw a mass assignment exception.
// Crud.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Crud extends Model { protected $fillable = ['title','post']; }
When you fill the title and post field in our form and submit the form, the new entry will be added to the database. We can confirm it by following the steps.
Step 13: Code index() function in the CRUDController File.
//CrudController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Crud; class CRUDController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $cruds = Crud::all()->toArray(); return view('crud.index', compact('cruds')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('crud.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $crud = new Crud([ 'title' => $request->get('title'), 'post' => $request->get('post') ]); $crud->save(); return redirect('/crud'); } /** * 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) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
Step 14: Need to update index.blade.php
<!-- index.blade.php --> @extends('master') @section('content') <div class="container"> <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Post</th> </tr> </thead> <tbody> @foreach($cruds as $post) <tr> <td>{{$post['id']}}</td> <td>{{$post['title']}}</td> <td>{{$post['post']}}</td> </tr> @endforeach </tbody> </table> </div> @endsection
Next, shoot the following URL.
http://localhost:8000/crud
You will see a table that has the id, title, and post-column with their respective data.
Step 15: Add Edit and Delete Button in the index.blade.php
<!-- index.blade.php --> @extends('master') @section('content') <div class="container"> <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Post</th> <th colspan="2">Action</th> </tr> </thead> <tbody> @foreach($cruds as $post) <tr> <td>{{$post['id']}}</td> <td>{{$post['title']}}</td> <td>{{$post['post']}}</td> <td><a href="{{action('CRUDController@edit', $post['id'])}}" class="btn btn-warning">Edit</a></td> <td><a href="{{action('CRUDController@destroy', $post['id'])}}" class="btn btn-danger">Delete</a></td> </tr> @endforeach </tbody> </table> </div> @endsection
Step 16: Create an edit function to pass the data to the edit view.
<?php // CRUDController.php /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $crud = Crud::find($id); return view('crud.edit', compact('crud','id')); }
Step 17: Create an edit view.
<!-- edit.blade.php --> @extends('master') @section('content') <div class="container"> <form method="post" action="{{action('CRUDController@update', $id)}}"> <div class="form-group row"> {{csrf_field()}} <input name="_method" type="hidden" value="PATCH"> <label for="lgFormGroupInput" class="col-sm-2 col-form-label col-form-label-lg">Title</label> <div class="col-sm-10"> <input type="text" class="form-control form-control-lg" id="lgFormGroupInput" placeholder="title" name="title" value="{{$crud->title}}"> </div> </div> <div class="form-group row"> <label for="smFormGroupInput" class="col-sm-2 col-form-label col-form-label-sm">Post</label> <div class="col-sm-10"> <textarea name="post" rows="8" cols="80">{{$crud->post}}</textarea> </div> </div> <div class="form-group row"> <div class="col-md-2"></div> <button type="submit" class="btn btn-primary">Update</button> </div> </form> </div> @endsection
Here we have used one more hidden field called the _method, a PATCH request to the server to update the data very quickly.
Step 18: Code update() in the CRUDController.
<?php // CRUDController.php /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $crud = Crud::find($id); $crud->title = $request->get('title'); $crud->post = $request->get('post'); $crud->save(); return redirect('/crud'); }
After filling the update form, we can see on the index page that our data is updated. So now only Delete functionality is remaining.
Step 19: Create a delete form to delete the data.
<!-- index.blade.php --> @extends('master') @section('content') <div class="container"> <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Post</th> <th colspan="2">Action</th> </tr> </thead> <tbody> @foreach($cruds as $post) <tr> <td>{{$post['id']}}</td> <td>{{$post['title']}}</td> <td>{{$post['post']}}</td> <td><a href="{{action('CRUDController@edit', $post['id'])}}" class="btn btn-warning">Edit</a></td> <td> <form action="{{action('CRUDController@destroy', $post['id'])}}" method="post"> {{csrf_field()}} <input name="_method" type="hidden" value="DELETE"> <button class="btn btn-danger" type="submit">Delete</button> </form> </td> </tr> @endforeach </tbody> </table> </div> @endsection
Step 20: Code the destroy() method in the CRUDController.
<?php // CRUDController.php /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $crud = Crud::find($id); $crud->delete(); return redirect('/crud'); }
Here in delete functionality, we have not put any confirm box, but it is okay for the demo. So I want you to take this demo and see how the laravel’ flow is working.
Output

There is some routes list in the resource controller. Type in the terminal: php artisan route:list
$ php artisan route:list +--------+-----------+------------------+--------------+---------------------------------------------+--------------+ | Domain | Method | URI | Name | Action | Middleware | +--------+-----------+------------------+--------------+---------------------------------------------+--------------+ | | GET|HEAD | / | | Closure | web | | | GET|HEAD | api/user | | Closure | api,auth:api | | | GET|HEAD | crud | crud.index | App\Http\Controllers\CRUDController@index | web | | | POST | crud | crud.store | App\Http\Controllers\CRUDController@store | web | | | GET|HEAD | crud/create | crud.create | App\Http\Controllers\CRUDController@create | web | | | GET|HEAD | crud/{crud} | crud.show | App\Http\Controllers\CRUDController@show | web | | | PUT|PATCH | crud/{crud} | crud.update | App\Http\Controllers\CRUDController@update | web | | | DELETE | crud/{crud} | crud.destroy | App\Http\Controllers\CRUDController@destroy | web | | | GET|HEAD | crud/{crud}/edit | crud.edit | App\Http\Controllers\CRUDController@edit | web |
If you are curious how resource controller works behind the scenes, then this is your answer.
Github: https://github.com/KrunalLathiya/Laravel54
Steps to use Github code
- Clone the repo in your local.
- Go to the root of the project and run the command “composer update.“
- Edit the .env file and use your MySQL database credentials.
- Run the command “php artisan migrate.“
- Now, we need to bootstrap the Laravel server, so run “php artisan serve.“
- If now, go to this URL: http://localhost:8000/crud/create.
hello sir i am new in laravel 5.4. I downloaded your project from github and when running your project gives an error “(1/1) NotFoundHttpException
in RouteCollection.php (line 179)” . i din’t modified any code just setup database connection.
Have you done composer install?
Please try below command in your root folder like : php artisan serve
Then go to this url : http://localhost:8000/crud/create
Thans a lot for this tutorial! I follow all of the steps but using diferent data ( a books table with ISBN title and Author fields) and I got all results OK You´re MASTER. Thanks again
Mauro Martin from Colombia
Glad to hear that my article helps you. Thank you
Hello Krunal I have same like this bt i am not getting the the view first of it was like blank page even i have added the source as you have mentioned after that it is displaying object not found.
I want to thank you for making these for beginners like me it is easy to use..
thanks
Please try below command in your root folder like : php artisan serve
Then go to this url : http://localhost:8000/crud/create
is it best practice to write query in controller instead of model in laravel?
Actually, we can go with both approaches. IF only CRUD operations are there then we definitely go with controller file but if there is more logic behind any of the modules then we can go with models. Also, some folks create services file and in that they write queries. So whatever approach suits to your application but make sure that if you are working in a team then all follow the same convention and flow.
sir, i have getting the error “Warning: require(C:\xampp\htdocs\Lvl54CRUD\bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Lvl54CRUD\bootstrap\autoload.php on line 17
Fatal error: require(): Failed opening required ‘C:\xampp\htdocs\Lvl54CRUD\bootstrap/../vendor/autoload.php’ (include_path=’.;C:\xampp\php\PEAR’) in C:\xampp\htdocs\Lvl54CRUD\bootstrap\autoload.php on line 17”
when i run your CRUD code…
pls reply…
Please first check your php version which is above 5.6 and then fire command composer install. I guess this will resolve your issue.
your files are missing
i have already installed composer…
then wt i can do to solve this….
Please try below command in your root folder like : php artisan serve
Then go to this url : http://localhost:8000/crud/create
Please, use composer install command and then go to routes >> web.php file check the routes in that file and according to that fire the URL
After step 14 , i get this error
(1/1) FatalErrorException
Class ‘AppHttpControllersCrud’ not found
in CRUDController.php (line 16)
in that CRUDController file
put
use AppCrud
It does not find any model that’s why
Same problem I faced 2. Thnaks for help
Hello! sir,
I faced same problem in step 14.
used ‘App\Crud’ , but still error.
thanks for your help.
sir I have problem with the database
when I create title and post then the information doesnt enter the database
how i can solve this problem?
Thanks for your help
Check the model was included properly or fill the protected $fillable field with your column fields.
After step 14, i get the error ErrorException
Undefined variable: cruds (View: ..\resources\views\crud\index.blade.php)
have you wrote this function in CRUDController,
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function index()
{
$cruds = Crud::all()->toArray();
return view(‘crud.index’, compact(‘cruds’));
}
Hi,
After 18 th step I am getting error “MethodNotAllowedHttpException”, even it’s not coming inside update function.
After google I came to know that this error might occur due to method type as in this update case it is PUT|PATCH. So what may be the cause of this issue. Any help
Rest works fine for me.
Thanks.
Use this inside your edit form:
input name=”_method” type=”hidden” value=”PATCH” tag
Excellent article.
Thanks!!!
Im Brazillian, congrats dude! Ill use to base for my all projects from now.
Hi. Thanks a lot for this one. This helps me a lot especially CRUD. Anyways my strength framework is codeigniter. Your code seems preety straigthforward and easy to understand.
Hi! I have been struggling for a while now. Please is there a way to create only an api with laravel without involving any form or anything? just an api that will interact with a mobile app. Thank you!
Yes, you if you are using Laravel 5.4 then you can use api.php file in routes folder. Define all the routes specific to your mobile application needs and then call the http request like api/ products or api/product/create. You need to remember that you have to always put a prefix api for every routes in api.php file.
I will right away take hold of your rss feed as I can not to find your e-mail subscription link or newsletter service. Do you have any? Kindly allow me realize so that I may subscribe. Thanks.
Nice guide. I am getting this error midway through it though
(1/1) FatalErrorException
Class ‘App\Http\Controllers\Crud’ not found
in CRUDController.php (line 16)
Include CRUD model in your controller like use AppCRUD;
Thank you!
Thank you!
Great post!
good
How to run this either local or on live site without “php artisan serve”?
Let me rephrase it. Because I’ve already knew to run locally through public but I just want to know how to run it without through public folder. In other words, correct me if I’m wrong but it seems I have to set VH on public folder and root of live site on public folder as well, am I right?
In the local, you can create virtual host and then your URL will like: laravelcrud.dev
Many Many Thanks For Providing Basic Knowledge of Laravel 5.4 with CRUD system in Detail.
Now I have Learn many thing from that Example.
Every code working properly.
Thanks again.
Thanks man
Thank you for this post. I now have a good understanding of how MVC works in Laravel.
I have xampp server and your crud application runs perfectly on my xampp server.
This tutorial really helped me a lot!! Thank you
Great!!! I am ruby programmer, and I’am starting with Laravel… This tutorial was perfect to got my first steps.
Thanks man
Very nice article.
To Much nice article Krunal
Thanks Krunal for the article. Helped a lot to me for my first CRUD.
excellent
Hi Krunal
really cool, but could you explain me the way data are stored in DB?
From the form tha action say “{{url(‘crud’)}}”, so how it call the store function?
Regards
Alessandro
I have used resource controller. please type php artisan route:list and there is a mapping of other CRUD operations routes already provided by Laravel
Hi Krunal,
Thanks for the tutorial. I have doubt regarding the populating of form data. Support we provide state and city as dropdown, if a state is selected then the cities corresponding to the state should populate the dropdown menu. is it possible to provide so in laravel. Kindly advise
Really nice bro, but why it doesn’t work with XAMPP server? It only works with server of ‘php artisan serve’. XAMPP server give me ‘not found’ or ‘404’ for views. Why?
you need to set up a virtual host for that.
You can also make it work in xampp by putting that folder inside htdocs and accessing using the url: http://localhost/Laravel54/public/crud in case you are not setting virtual host.
Hai sir, How about this coment in cmd when i working step 3,
[Illuminate\Database\QueryException]
SQLSTATE[HY000] [1045] Access denied for user ‘root’@’localhost’ (using password: YES) (SQL: select * from informat
ion_schema.tables where table_schema = laravel154 and table_name = migrations)
Please set up a database first with actual name in .env file and phpmyadmin.
If you receive an SQL Error:
“SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long;”
Add to app/Providers/AppServiceProvider.php:
-before class name
use Illuminate\Support\Facades\Schema;
-inside class
public function boot()
{
Schema::defaultStringLength(191);
}
Thanks Ibnu…this helped me.
Thank You Krunal
Delete is not working. what went wrong . Is delete need a form also?
Wow this post is amazing and direct to the point 🙂 its totally helpful cheers man !!
Thanks a lot for this tutorial and the github resources! It really helps me a lot!
Thanks a lot for this tutorial.. It really helps me a lot..
thank you sir
One of the best Laravel CRUD post i have seen. Everything is working fine.
Just add one Button New Post in index.blade.php which calls to CRUDController@create to achieve all functionality from one page.
THANK YOU
its say method not allowed in destroy function
Great tutorial. Thanks for saving my time. (get in stuck on my app on Update page)
You missed important note :
Put that code below your DELETE form.
Can you help me out? After step 10 when I want to go to the http://localhost:8000/crud/create it gives me a fatal error.
(1/1) FatalErrorException
syntax error, unexpected ‘<'
in 29f1e490dd283e44eb226b331436a3728d47b890.php (line 8)
Help would be awesome, thanks!
Thank you. Appreciated tutorial.
Why if don’t access url http://localhost:8000/crud/create ?
very good article
thank you for sharing.
Hello Contact me please
Hi Krunal,
Thank you so much for your helpful curd operation.
Please solve my problem. when i edit data is not working proper its route is going in show function while submit data. please find below code.
1.Edit file
Back
{{csrf_field()}}
{{–
ID
id}}”>
–}}
Title
title}}”>
Description
description}}”>
Update
2. This controller page
public function show($id)
{
$read = blogs::findOrFail($id);
return view(‘blogread’,compact(‘read’,’id’));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function edit($id)
{
$editdata= blogs::find($id);
return view(‘blogedit’, compact(‘editdata’,’id’));
}
/**
* Update the specified resource in storage.
*
* @param IlluminateHttpRequest $request
* @param int $id
* @return IlluminateHttpResponse
*/
public function update($id,Request $request)
{
$data= blogs::find($id);
$data->title=$request->get(‘title’);
$data->description=$request->get(‘description’);
$data->save();
return ‘data is updated’;
}
Great Tutorial! Worked perfectly!
thanks its really helps me a lot .easily i learned all the steps instead of laravel documentation.great tutorial.
hello,
i have one error ocurs everytime in new project create and apply for php artisan migrate
every time occur same error
User table is already exits..
so what can i do??
You have previously migrated the table, that is why user table already exists.
Thank you. Good tutorial
I was helped a lot by what you made
Thanks man. Its helps me a lot. God bls u!
At step 11 you have given the form action url as action=”{{url(‘crud’)}}” but insert query is written in create function in crud controller . How did it worked? You didn’t mentioned the function name in form action.