Laravel 5.5 CRUD Tutorial Example Step By Step From Scratch
Laravel 5.5 CRUD Tutorial Example Step By Step From Scratch is today’s leading topic. We are going to make Ticket System Project In Laravel 5.5. So let us get started.
Laravel 5.5 CRUD Tutorial
First of all, we will make one Laravel Project and then step by step; we will build this project. Ticket System is ultimately a Laravel 5.5 CRUD Operations, that is why my focus is on Laravel CRUD.
Step 1: Configure Laravel 5.5 Project.
Install the brand new Laravel Project by the typing following command.
composer create-project laravel/laravel --prefer-dist crud55
Next, configure the database in the .env file.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=crud55 DB_USERNAME=root DB_PASSWORD=mysql
Okay, now we need to make one schema for the database.
Now, this is Ticket’s table schema.
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTicketsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tickets', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id'); $table->string('title'); $table->string('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tickets'); } }
Run the following command.
php artisan migrate
It will create the tables in the database.
Step 2: Laravel Authentication.
Laravel 5.5 Provides us Authentication out of the box. Just type the following command.
php artisan make:auth
Start the Laravel server by the following command.
php artisan serve
We can register the user by the following URL: http://localhost:8000/register
Step 3: Make models and controllers for our application.
We need to make TicketController.
Type the following cmd in the terminal.
php artisan make:controller TicketController
Also, make the models for the same. The User model is already there, so no need to create again.
php artisan make:model Ticket
Step 4: Create the views for our application.
Make one user folder and in that make one file called create.blade.php.
@extends('layouts.app') @section('content') <div class="container"> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div><br /> @endif <div class="row"> <form method="post" action="{{url('/create/ticket')}}"> <div class="form-group"> <input type="hidden" value="{{csrf_token()}}" name="_token" /> <label for="title">Ticket Title:</label> <input type="text" class="form-control" name="title"/> </div> <div class="form-group"> <label for="description">Ticket Description:</label> <textarea cols="5" rows="5" class="form-control" name="description"></textarea> </div> <button type="submit" class="btn btn-primary">Create</button> </form> </div> </div> @endsection
Now, make a route to get this file.
Route::get('/create/ticket','TicketController@create');
Also, write the controller get function.
/** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('user.create'); }
To store the data in a database, first, we need to prevent the mass assignment exception.
So, in the Ticket.php model, add the following attribute.
protected $fillable = ['user_id', 'title', 'description'];
Create one web route to handle the post request.
Route::post('/create/ticket','TicketController@store');
Include Ticket.php model into the TicketController.php file and write the store function code.
use App\Ticket; /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $ticket = new Ticket(); $data = $this->validate($request, [ 'description'=>'required', 'title'=> 'required' ]); $ticket->saveTicket($data); return redirect('/home')->with('success', 'New support ticket has been created! Wait sometime to get resolved'); }
Also, we have created the saveTicket() function into the model.
public function saveTicket($data) { $this->user_id = auth()->user()->id; $this->title = $data['title']; $this->description = $data['description']; $this->save(); return 1; }
Step 5: Display the tickets.
In the home.blade.php file, write the following code.
@extends('layouts.app') @section('content') <div class="container"> @if(\Session::has('success')) <div class="alert alert-success"> {{\Session::get('success')}} </div> @endif <div class="row"> <a href="{{url('/create/ticket')}}" class="btn btn-success">Create Ticket</a> <a href="{{url('/tickets')}}" class="btn btn-default">All Tickets</a> </div> </div> @endsection
Make one route for the listing of the tickets.
Route::get('/tickets', 'TicketController@index');
/** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $tickets = Ticket::where('user_id', auth()->user()->id)->get(); return view('user.index',compact('tickets')); }
Create one index.blade.php file inside user folder.
@extends('layouts.app') @section('content') <div class="container"> <table class="table table-striped"> <thead> <tr> <td>ID</td> <td>Title</td> <td>Description</td> <td colspan="2">Action</td> </tr> </thead> <tbody> @foreach($tickets as $ticket) <tr> <td>{{$ticket->id}}</td> <td>{{$ticket->title}}</td> <td>{{$ticket->description}}</td> <td>Edit</td> <td>Delete</td> </tr> @endforeach </tbody> </table> <div> @endsection
Step 6: Make edit view and write update function.
// web.php Route::get('/edit/ticket/{id}','TicketController@edit'); Route::post('/edit/ticket/{id}','TicketController@update');
Switch to the controller and write the edit function.
/** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $ticket = Ticket::where('user_id', auth()->user()->id) ->where('id', $id) ->first(); return view('user.edit', compact('ticket', 'id')); }
Write edit.blade.php file.
@extends('layouts.app') @section('content') <div class="container"> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div><br /> @endif <div class="row"> <form method="post" action="{{action('TicketController@update', $id)}}" > {{csrf_field()}} <input name="_method" type="hidden" value="PATCH"> <div class="form-group"> <input type="hidden" value="{{csrf_token()}}" name="_token" /> <label for="title">Ticket Title:</label> <input type="text" class="form-control" name="title" value={{$ticket->title}} /> </div> <div class="form-group"> <label for="description">Ticket Description:</label> <textarea cols="5" rows="5" class="form-control" name="description">{{$ticket->description}}</textarea> </div> <button type="submit" class="btn btn-primary">Update</button> </form> </div> </div> @endsection
Also, write the update function.
/** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $ticket = new Ticket(); $data = $this->validate($request, [ 'description'=>'required', 'title'=> 'required' ]); $data['id'] = $id; $ticket->updateTicket($data); return redirect('/home')->with('success', 'New support ticket has been updated!!'); }
Also, code the model function updateTicket().
public function updateTicket($data) { $ticket = $this->find($data['id']); $ticket->user_id = auth()->user()->id; $ticket->title = $data['title']; $ticket->description = $data['description']; $ticket->save(); return 1; }
Step 7: Code the delete ticket function.
Define the route for the function.
Route::delete('/delete/ticket/{id}','TicketController@destroy');
Now, full index.blade.php view is like the following.
@extends('layouts.app') @section('content') <div class="container"> <table class="table table-striped"> <thead> <tr> <td>ID</td> <td>Title</td> <td>Description</td> <td colspan="2">Action</td> </tr> </thead> <tbody> @foreach($tickets as $ticket) <tr> <td>{{$ticket->id}}</td> <td>{{$ticket->title}}</td> <td>{{$ticket->description}}</td> <td><a href="{{action('TicketController@edit',$ticket->id)}}" class="btn btn-primary">Edit</a></td> <td> <form action="{{action('TicketController@destroy', $ticket->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
The whole TicketController.php file looks like the following.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Ticket; class TicketController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $tickets = Ticket::where('user_id', auth()->user()->id)->get(); return view('user.index',compact('tickets')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('user.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $ticket = new Ticket(); $data = $this->validate($request, [ 'description'=>'required', 'title'=> 'required' ]); $ticket->saveTicket($data); return redirect('/home')->with('success', 'New support ticket has been created! Wait sometime to get resolved'); } /** * 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) { $ticket = Ticket::where('user_id', auth()->user()->id) ->where('id', $id) ->first(); return view('user.edit', compact('ticket', '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) { $ticket = new Ticket(); $data = $this->validate($request, [ 'description'=>'required', 'title'=> 'required' ]); $data['id'] = $id; $ticket->updateTicket($data); return redirect('/home')->with('success', 'New support ticket has been updated!!'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $ticket = Ticket::find($id); $ticket->delete(); return redirect('/home')->with('success', 'Ticket has been deleted!!'); } }
Finally, our Laravel 5.5 CRUD Tutorial Example Step By Step From Scratch is over.
edit.blade.php line 17 should be POST no PATCH if there is no patch route.
The edit.blade.php file is OK if the route verb is changed to patch like this:
Route::patch(‘/edit/ticket/{id}’,’TicketController@update’);
in the routes/web.php file
Thanks for posting the tutorial Krunal!
Thanks a lot bro. I was struck with lots of issues in CRUD. With your help now i have clear idea about CRUD.
I get this SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_s
chema.tables where table_schema = LaravelTutorial and table_name = migratio
ns)
When trying to `php artisan migrate` in the first step
Please start your database mysql server.
when i fill the title and description box and clicked on create button then
“Trying to get property of non-object” this error comes
You are trying to get the property of an object that does not exist. So try to dd the variable
Can you please elaborate this? As I’m getting same error.
I think, he is saying var_dump the variable such as ” var_dump($variable)” in the controller. To check whether the variable is exist or not.
ok
Thanks for the tutorial Kruna ,
I have an error getting the value in the field ( Trying to get property ‘title’ of non-object (View: )
input type=”text” class=”form-control” name=”title” value={{$ticket->title}} />
already solve, my query was bad and the label I have to put it like this,
value=”{{$title->title}}”
thanks
thanks for this tutorial its nice but beginners is always tempted on copy and paste. well this is still a nice crud tutorial. thank alot.
in create.blade.php action=”{{url(‘/create/ticket’)}}”> and Route::get(‘/create/ticket’,’TicketController@create’); ??????? hahaha
Please read the full example, it is to show create a view. After that, I have mentioned the post route as well. Do not be lazy, Read full example.
where do I write the schema please?
Hello, thanks for your tutorials !
I’ve a question, how can id multiple records with this code ?
For example, I will record 10 times title+description with one button submit.
Thanks, very helpful
hye how to declare table name ?
In model file just define a property like: protected $table = ‘your table name’
Can You Please help me to resolve some issues.
how to do if I will record 10 times title+description with one button submit ? Thanks Krunal
i cant insert
I am beginner in laravel..$ data is not getting passed to the query(model)Values are going as null..App is bombing..for edit and create is method save().Kindly advice
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Class ‘App\Http\Controllers\Ticket’ not found
Write this code at the top of the controller: use AppTicket;
Hi
First of all this tutorial is very good….
Actually everything is working fine for me except the updation part i am getting the below error while updating
MethodNotAllowedHttpException
No message
I also tried the sukhi’s answer at the top but still i am getting the same error
At which step, please specify that.
i am facing the same issue like Jayant. The issue occurs when submitting a change to existing ticket in edit.blade.php page.
any clue how to fix it?
PS: i am using laravel 5.6
Hi, Please edit the update route and change with given below route. It should be like:
Route::patch(‘/edit/ticket/{id}’,’TicketController@update’);
thanks
in the update function don’ t you need update especific id in the table by find the id passed to route??
if yes please give-me a example how to do update in this case using save method.
Dear Krunal,
Hi this is Ram,
I want to store data into 4 different tables using laravel where first table id is the primary id and remaining tables it will be the foreign key. This will be like the registration form for job applicant.Can you please suggest me the code how to store the values in 4 tables.
SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘title’ cannot be null
Please help
Your title column’s post value is null. Check your input box’s name attribute.
hell0 thanks a lot
thanks.
Thanks Bro, I have created my first ever Laravel Project with your reference. A whole day, and i am able to complete it.
Call to undefined method AppUser::id()
Very helpful. I enrolled udemy course that was not helpful in learning CRUD. I search for a complete example and here is you. Thank You So Much.
Many thanks for the tutorial, it helped me get started with Laravel 🙂
As the first comment in the thread mentions, you have used a PATCH in edit.blade.php, whilst the routes has
Route::post(‘/edit/ticket/{id}’,’TicketController@update’);
This leads to a MethodNotAllowedHttpException.
Changing the above to:
Route::patch(‘/edit/ticket/{id}’,’TicketController@update’);
Fixes this.
Also would the resources/views/user folder not better be called resources/views/ticket ?
Your update route is wrong. It should be patch. Those who are getting error please change the route for update. It should be like :
Route::patch(‘/edit/ticket/{id}’,’TicketController@update’);
thanks
Fantastic work brother Thank you so much.
I’m new on laravel, I found some bug on edit.blad.php line 21 while we fill the value on value field you miss the ” “(quote), I face this issue while i’m trying to fetch data i found this issue, So buddy please look at thus file.
And again thank a lot brother for this amazing and easy to understand article.
very nice article. it really helped me
Very Good Explain !! Well done keep posting
ErrorException (E_WARNING)
Declaration of App\Ticket::update(App\Request $request, $id) should be compatible with Illuminate\Database\Eloquent\Model::update(array $attributes = Array, array $options = Array)
I Get this error. can you help me?
layouts.app file definition missing bro, how to add