Laravel 5.5 Tutorial With Example From Scratch is Laravel 5.5 CRUD tutorial for beginners. Laravel has recently launched its new version called Laravel 5.5, and it is also come up with a bunch of new Features. Today, we are not discussing in depth new features of Laravel 5.5, just list them but rather than focusing on the coding in Laravel 5.5. It’s small application in Laravel 5.5. Laravel is most flexible and elegant PHP Framework so far and always come up with new things. Laravel is the best representation of PHP Language in my opinion. It is the by far most in built functionality Framework. Creator has seriously put his own heart to make it and right now maintaining. Every Laravel events, we will see there is always new and new coming ready with this Framework, and that is why It is the most trusted framework among the PHP Community. It provides us the power to whatever we can build and play with this structure, with in scope and also with out its scope if you have in-depth knowledge of Latest PHP version.
Content Overview
- 1 Laravel 5.5 New Features
- 2 Installation Requirments
- 3 Laravel 5.5 CRUD Tutorial From Scratch
- 4 Step 1: Installing The Laravel 5.5 Framework.
- 5 Step 2: Setup a MySQL database in .env file.
- 6 Step 3: Create a model as well as migration file for our Products table.
- 7 Step 4: Make one view file to add the form data in the database.
- 8 Step 5: Create one controller and route to display the Product form
- 9 Step 6: Put the Laravel 5.5 Validation in Product Form.
- 10 Step 7: Make an index page to list the products.
- 11 Step 8: Make an edit view for update the products.
- 12 Step 9: Delete the product.
Laravel 5.5 New Features
- Custom validation rules object.
- Returns response data from the validator.
- Improvements with the default error views.
- Great support for the custom error reporting.
- Support for email themes in mailable.
- We can render mailable in the browser.
- Vendor packages have provider support.
- It adds front end presets, which means we can use Vue, React.js or none of them if we want.
- Laravel Migrate Fresh command.
- Whoops, which was there in Laravel 4.2 is back in Laravel 5.5
- Laravel Package Auto Discovery.
Installation Requirments
- PHP >= 7.0.0
- OpenSSL PHP Extension
- PDO PHP Extension
- Mbstring PHP Extension
- Tokenizer PHP Extension
- XML PHP Extension
Laravel 5.5 CRUD Tutorial From Scratch
Step 1: Installing The Laravel 5.5 Framework.
composer create-project --prefer-dist laravel/laravel Laravel55
It will create a directory and install all the Laravel specific dependencies.
Step 2: Setup a MySQL database in .env file.
Create one database in MySQL and then switch to your editor and open the .env file.
// .env DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=Laravel55 DB_USERNAME=root DB_PASSWORD=mysql
I have setup my local database credentials. You just need to change last three constants and you are ready to go.
Now, migrate two tables provided by Laravel 5.5. Switch to your terminal and type following command.
php artisan migrate
It will create two tables in your database.
- users
- password_resets
Step 3: Create a model as well as migration file for our Products table.
Type the following command in your terminal.
php artisan make:model Product -m
It will create two files.
- Product.php model.
- create_products_table migration file.
We need to create Schema for the products table. So navigate to Laravel55 >> database >> migrations >> create_products_table.
// create_products_table public function up() { Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->integer('price'); $table->timestamps(); }); }
So, for our products table, there will be 5 columns. timestamps() have 2 columns
- created_at
- updated_at
Now, migrate the table by the following command.
php artisan migrate
In the database, you can see the products table.
Step 4: Make one view file to add the form data in the database.
Make one folder called products and then create a file in the resources >> views >> products >> create.blade.php and put the following code in it.
<!-- create.blade.php --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Laravel 5.5 CRUD Tutorial With Example From Scratch </title> <link rel="stylesheet" href="{{asset('css/app.css')}}"> </head> <body> <div class="container"> <h2>Create A Product</h2><br /> <form method="post"> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="name">Name:</label> <input type="text" class="form-control" name="name"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="price">Price:</label> <input type="text" class="form-control" name="price"> </div> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <button type="submit" class="btn btn-success" style="margin-left:38px">Add Product</button> </div> </div> </form> </div> </body> </html>
Step 5: Create one controller and route to display the Product form
Go to the terminal and type the following command.
php artisan make:controller ProductController --resource
It will create one controller file called ProductController.php and It has all the CRUD Functions, we need to seek.
Here, we have used resource parameter, so by default, It provides us some routing patterns, but right now, we will not see until we register one route in routes >> web.php file. So let us do it.
// web.php Route::resource('products','ProductController');
Now, switch to your terminal and type the following command.
php artisan route:list
You will see following route list.
Next step would be to go to ProductController.php file and add into create() function some code.
// ProductController.php /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('products.create'); }
After that, we need to start Laravel Development server. So in the terminal, hit the following command.
php artisan serve
Switch to the browser and hit this URL: http://localhost:8000/products/create
You will see the following screen.
Step 6: Put the Laravel 5.5 Validation in Product Form.
First, we need to apply an action to our product creation form.
<!-- create.blade.php --> <form method="post" action="{{url('products')}}">
Now, we need to handle CSRF issue. So, put the following code in the form
<!-- create.blade.php --> {{csrf_field()}}
We also need to handle Mass Assignment Exception. So we need to go to app >> Product.php file and in that put the protected $fillable property in it.
// Product.php protected $fillable = ['name','price'];
If you see the resource routes then it has post request has ‘/products‘ route and store function in ProductController.php file. So we need to code the store function in order to save the data in the database.
One thing to keep in mind that, we need to include the namespace of Product.php model in the ProductController.php file. So type the following line at the starting of ProductController.php file.
use App\Product;
Also, we need to put the validation there.
// ProductController.php /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $product = $this->validate(request(), [ 'name' => 'required', 'price' => 'required|numeric' ]); Product::create($product); return back()->with('success', 'Product has been added');; }
Now, if validation fails then we need to show an error. So go back to create.blade.php and put the following code after h2 tag.
<!-- create.blade.php --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Laravel 5.5 CRUD Tutorial With Example From Scratch </title> <link rel="stylesheet" href="{{asset('css/app.css')}}"> </head> <body> <div class="container"> <h2>Create A Product</h2><br /> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div><br /> @endif @if (\Session::has('success')) <div class="alert alert-success"> <p>{{ \Session::get('success') }}</p> </div><br /> @endif <form method="post" action="{{url('products')}}"> {{csrf_field()}} <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="name">Name:</label> <input type="text" class="form-control" name="name"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="price">Price:</label> <input type="text" class="form-control" name="price"> </div> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <button type="submit" class="btn btn-success" style="margin-left:38px">Add Product</button> </div> </div> </form> </div> </body> </html>
At last, go to the browser and hit the development Laravel URL: http://localhost:8000
If you submit the form without any value then, you can see the errors like below image.
If you fill all the values then, you will redirect to this page with the success message. So, here One thing must be noticed.
// ProductController.php public function store(Request $request) { $product = $this->validate(request(), [ 'name' => 'required', 'price' => 'required|numeric' ]); Product::create($product); return back()->with('success', 'Product has been added'); }
Step 7: Make an index page to list the products.
For that, first, we need to send the data to the index.blade.php. So, in ProductController.php file, we need to write the code to fetch the data and return it to the index view.
// ProductController.php /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $products = Product::all()->toArray(); return view('products.index', compact('products')); }
In resources >> views >> products, create one blade file called index.blade.php file and put the following code in it.
<!-- index.blade.php --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Index Page</title> <link rel="stylesheet" href="{{asset('css/app.css')}}"> </head> <body> <div class="container"> <br /> @if (\Session::has('success')) <div class="alert alert-success"> <p>{{ \Session::get('success') }}</p> </div><br /> @endif <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Price</th> <th colspan="2">Action</th> </tr> </thead> <tbody> @foreach($products as $product) <tr> <td>{{$product['id']}}</td> <td>{{$product['name']}}</td> <td>{{$product['price']}}</td> <td><a href="{{action('ProductController@edit', $product['id'])}}" class="btn btn-warning">Edit</a></td> <td> <form action="{{action('ProductController@destroy', $product['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> </body> </html>
So, when you hit the URL: http://localhost:8000/products
Step 8: Make an edit view for update the products.
Our step will be to add the edit function in ProductController.php file and put the following code in it.
// ProductController.php /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $product = Product::find($id); return view('products.edit',compact('product','id')); }
Now, make an edit.blade.php file inside resources >> views >> products
<!-- edit.blade.php --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Laravel 5.5 CRUD Tutorial With Example From Scratch </title> <link rel="stylesheet" href="{{asset('css/app.css')}}"> </head> <body> <div class="container"> <h2>Edit A Product</h2><br /> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div><br /> @endif <form method="post" action="{{action('ProductController@update', $id)}}"> {{csrf_field()}} <input name="_method" type="hidden" value="PATCH"> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="name">Name:</label> <input type="text" class="form-control" name="name" value="{{$product->name}}"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="price">Price:</label> <input type="text" class="form-control" name="price" value="{{$product->price}}"> </div> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <button type="submit" class="btn btn-success" style="margin-left:38px">Update Product</button> </div> </div> </form> </div> </body> </html>
A further step would be to code the update function.
// ProductController.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) { $product = Product::find($id); $this->validate(request(), [ 'name' => 'required', 'price' => 'required|numeric' ]); $product->name = $request->get('name'); $product->price = $request->get('price'); $product->save(); return redirect('products')->with('success','Product has been updated'); }
Step 9: Delete the product.
// ProductController.php /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $product = Product::find($id); $product->delete(); return redirect('products')->with('success','Product has been deleted'); }
Our Laravel 5.5 CRUD Tutorial With Example From Scratch is over. I put the Github Link over here.
Github Steps:
- Clone the repository.
- Type this command: composer update
- Configure the database in the .env file.
- Start the Laravel development server: php artisan serve
- Switch to the URL: http://localhost:8000/products/create
Remember that we can now use “php artisan make:model -a” to create “everything” (factory, migration, model, and resource controller, all in one. It’s not even documented yet 🙂
Here’s the relevant code from ModelMakeCommand.php in the laravel/framework core.
if ($this->option(‘all’)) {
$this->input->setOption(‘factory’, true);
$this->input->setOption(‘migration’, true);
$this->input->setOption(‘controller’, true);
$this->input->setOption(‘resource’, true);
}
Wow, a very useful tutorial for newcomers – This has helped me a lot. Thanks for putting in the effort!
Thanks / great tutorial hopwfully you make advanced as we learned this
Hello, I get the following error: “Class ‘App\Http\Controllers\Product’ not found”
write this in the controller : use AppProduct;
Nice tutorial. Worked Perfectly 🙂 Thanks for putting in the effort!
man, it’s very awesome tutorial. thank you so much
i am getting this error when i put the name and the price and click on Add product button, what could be the problem?
(1/1) ErrorException
Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, null given, called in C:\Users\Andres\Desktop\laravel\Laravel55\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on line 1374 and defined
Change the store function into
public function store(Request $request)
{
$product = $this->validate(request(), [
‘name’ => ‘required’,
‘price’ => ‘required|numeric’
]);
Product::create($request->all());
return back()->with(‘success’, ‘Product has been added’);
}
Thank you. Very good and easy.
Hi, I am getting error like this “InvalidArgumentException View [products.create] not found.”
My file name and code like this tutorial, any solutin everyone ? Thx
you need to make one directory inside resources/views folder called products. Inside make one file called create.blade.php
same error.nothing changed and I already had create.blade.php. any suggestion?
How about a delete confirm box before actually deleting?
why my edit is blank ?
thanks
This is a very useful tutorial, simple but clear enough for beginners (like me)!
Thanks a lot!
i’m beginner, its just i cant see create button or code so i add them for my self, cheers, and not a problem
Thank you for helping us. Very useful
Am grateful, very grateful
nice tutorial
I’ve this problem: Undefined variable: id
when I want to Update in edit.blade.php
I put the same code :
In my controller I´ve the same code of tutorial.
please pass the id like this: return view(‘products.edit’,compact(‘product’,’id’)); You can access id variable inside edit.blade.php file.
Helllo bro you Doing Wonder Full Work ..
i have a one problem to follow your tutorial ..
when i am submit form this error display:
” The page has expired due to inactivity.
Please refresh and try again. ”
what should i do now..
You need to include CSRF token. If your laravel version is 5.6 then after form tag writes like this: @csrf. It will help you to get rid of that error.
incredible tut, thanks a lot..helpfull for newbi like me…good job
Good job bro, that’s what I call a tutorial.
A pure check list of things to do and that you must always do, that is what a tutorial always must be.
What ever is complicated your aplication, in fact a web application is just a formular to create datas, validation of the created datas, insert datas, show datas, modify datas, delete datas, nothing less, nothing more.
I am new in Laravel, and my OS is W7 and I use different WAMP such as Laragon or Wampserver64.
At Step 2, with Laragon I did not have any problem with the command :
>php artisan migrate
But with Wampserver64 (who is probably the WAMP environement who is the most used on Windows)
I received this bad answer :
Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))
To fix this bug, I edited config\database.php and changed
‘mysql’ => [
…
‘charset’ => ‘utf8mb4’,
‘collation’ => ‘utf8mb4_unicode_ci’,
…
],
To
‘mysql’ => [
…
‘charset’ => ‘utf8’,
‘collation’ => ‘utf8_unicode_ci’,
…
],
After I DROP manually the users TABLE because the command
>php artisan migrate:reset
says : Nothing to rollback
and relaunched the command :
>php artisan migrate
and evrething was fine.
PS : If you want to modify your tutorial, I can send you the complete result of the two commands php artisan migrate.
PS2 : All my apologies for my english, I learnt it in a far far away galaxy named french public school.
Krunal,
It’s good job for a intermediate developer!
Nazim
A real nice tutorial. Never touched laravel before this…
You are amazing man!
Thanks so much for this tutorial.
I get the following error. tried all config:clear, cache:clear, composer install and composer update.
But not yet fixed. What should I do? Thanks
Warning: require_once(C:\xampp\htdocs\Laravel55/../bootstrap/app.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Laravel55\index.php on line 38
Fatal error: require_once(): Failed opening required ‘C:\xampp\htdocs\Laravel55/../bootstrap/app.php’ (include_path=’C:\xampp\php\PEAR’) in C:\xampp\htdocs\Laravel55\index.php on line 38
Best tutorial I’ve found yet. Thanks a lot.
Thanks, keep learning and sharing!!
Nice Tutorial
Hi Krunal,
When we click on the add product button in create.blade.php, how it call to store method of ProductController.