AppDividend
Latest Code Tutorials

Laravel 5.5 CRUD Tutorial Example Step By Step From Scratch

37,224

Get real time updates directly on you device, subscribe now.

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.

Related Posts
1 of 37
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.

 

28 Comments
  1. edu says

    edit.blade.php line 17 should be POST no PATCH if there is no patch route.

    1. Suki says

      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!

  2. SAMUEL says

    Thanks a lot bro. I was struck with lots of issues in CRUD. With your help now i have clear idea about CRUD.

  3. Matt says

    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

    1. Krunal says

      Please start your database mysql server.

  4. akash says

    when i fill the title and description box and clicked on create button then

    “Trying to get property of non-object” this error comes

    1. Krunal says

      You are trying to get the property of an object that does not exist. So try to dd the variable

  5. ronald mojica says

    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}} />

    1. ronald mojica says

      already solve, my query was bad and the label I have to put it like this,

      value=”{{$title->title}}”
      thanks

  6. zodiac says

    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.

  7. muy mal says

    in create.blade.php action=”{{url(‘/create/ticket’)}}”> and Route::get(‘/create/ticket’,’TicketController@create’); ??????? hahaha

    1. Krunal says

      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.

  8. Samson says

    where do I write the schema please?

  9. Vali says

    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.

  10. Ahmed Ragala says

    Thanks, very helpful

  11. firdaus says

    hye how to declare table name ?

    1. Krunal says

      In model file just define a property like: protected $table = ‘your table name’

  12. Vali says

    how to do if I will record 10 times title+description with one button submit ? Thanks Krunal

  13. Kevin says

    i cant insert

  14. laks says

    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

  15. Inamulhasan says

    Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
    Class ‘App\Http\Controllers\Ticket’ not found

    1. Krunal says

      Write this code at the top of the controller: use AppTicket;

  16. jayant says

    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

    1. jayant says

      I also tried the sukhi’s answer at the top but still i am getting the same error

    2. Krunal says

      At which step, please specify that.

      1. Jan says

        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

  17. Albertino Carvalho says

    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.

  18. Ram says

    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.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.