简体   繁体   English

如何在laravel 5.2中更新数据库表

[英]How to update a database table in laravel 5.2

i created one project in laravel 5.2. 我在laravel 5.2中创建了一个项目。 In that "myform.blade.php" page , created form for register the user. 在该“ myform.blade.php”页面中,创建了用于注册用户的表单。 after registration it will show the current user in table format("index.blade.php"). 注册后,它将以表格格式(“ index.blade.php”)显示当前用户。 There i given two dynamic button like the drop inside the table. 在那里,我给了两个动态按钮,就像桌子内的桌子。 One for Edit and other for Edit/View. 一个用于编辑,另一个用于编辑/查看。 When i click on delete button it will delete the corresponding row from the database by taken Primary key(employeeID) as reference id, it's working properly. 当我单击删除按钮时,它将以主键(employeeID)作为参考ID从数据库中删除相应的行,它工作正常。 if i click on Edit/View button it will redirect to "edit.blade.php". 如果我单击“编辑/查看”按钮,它将重定向到“ edit.blade.php”。 There i created same form as in myform.blade.php. 在那里,我创建了与myform.blade.php中相同的表单。 If we want to edit the details we can edit from there. 如果要编辑详细信息,可以从那里进行编辑。 I can able to fetch the data from database to the form that i created in the "edit.blade.php". 我可以从数据库中获取数据到在“ edit.blade.php”中创建的表单。 But i don't know how to update the data from their without inserting the same data again(It is not possible, because it will create Integrity constraint violation by trying to insert duplicate primary key. Can any one please tell me how to do updation. Replies are appreciable. 但是我不知道如何在不再次插入相同数据的情况下从其更新数据(这是不可能的,因为它会通过尝试插入重复的主键来创建违反Integrity约束的行为。任何人都可以告诉我如何进行更新答复是可观的。

"myform.blade.php" is “ myform.blade.php”是

  @extends('app')

@section('content')

    <div class="templatemo-content-wrapper">
        <div class="container">
            <ol class="breadcrumb">
                <li><a href="{{ url("/") }}"><font color="green">Home</font></a></li>
                <li class="active">Employee Form</li>
            </ol>
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <div class="panel panel-success">
                        <div class="panel-heading">Employee Form</div>
                        <div class="panel-body">
                            @if (count($errors) > 0)
                                <div class="alert alert-danger">
                                    <strong>Whoops!</strong> There were some problems with your input.<br><br>
                                    <ul>
                                        @foreach ($errors->all() as $error)
                                            <li>{{ $error }}</li>
                                        @endforeach
                                    </ul>
                                </div>
                            @endif

                            <form class="form-horizontal" role="form" method="POST" action="{{ url('myform/myform/') }}">
                                <input type="hidden" name="_token" value="{{ csrf_token() }}">

                                <div class="form-group">
                                    <label class="col-md-4 control-label">Employee ID</label>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" name="employeeID" value="{{ old('employeeID') }}" placeholder="Enter employee ID">
                                    </div>
                                </div>


                                <div class="form-group">
                                    <label class="col-md-4 control-label">E_number</label>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" name="employeeNo" value="{{ old('employeeNo') }}" placeholder="Enter employee number">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-md-4 control-label">Name</label>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" name="Cname" value="{{ old('Cname') }}" placeholder="Enter Contact Name">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-md-4 control-label">DOB</label>
                                    <div class="col-md-6">
                                        <input type="date" class="form-control" name="dob" value="{{ old('dob') }}" placeholder="Enter date of birth">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-md-4 control-label">Contact Phone</label>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" name="phoneNumber" value="{{ old('phoneNumber') }}" placeholder="Enter Mobile Number">
                                    </div>
                                </div>



                                <div class="form-group">
                                    <label class="col-md-4 control-label">Address</label>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" name="address" value="{{ old('address') }}" placeholder="Enter Address">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <div class="col-md-6 col-md-offset-4">
                                        <button type="submit" class="btn btn-warning">
                                            Save
                                        </button>
                                    </div>
                                </div>

                                <a href="{{ url('myform/index') }}">view Data</a>

                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


@endsection

"index.blade.php" is “ index.blade.php”是

 @extends('app')

@section('content')


    <div class="templatemo-content-wrapper" xmlns="http://www.w3.org/1999/html">
        <ol class="breadcrumb">
            <li><a href="{{ url("/") }}"><font color="green">Home</font></a></li>
            <li class="active">user information</li>
        </ol>
        <div class="templatemo-content">

            <h1>View/Edit user information</h1>

            <div>
                <div>
                    <div>

                        <table id="example" class="table table-striped table-hover table-bordered" bgcolor="#fff8dc">
                            <thead>
                            <tr>
                                <th>Employee ID</th>
                                <th>Employee No</th>
                                <th>Contact Name</th>
                                <th>Date of birth</th>
                                <th>Mobile number</th>
                                <th>address</th>

                            </tr>
                            </thead>
                            <tbody>

                            {{--{{ UserController::getIndex() }}--}}
                            @foreach($employer as $emp)
                                <tr>
                                    <td>{{ $emp->employeeID }}</td>
                                    <td>{{ $emp->employeeNo }}</td>
                                    <td>{{ $emp->Cname }}</td>
                                    <td>{{ $emp->dob }}</td>
                                    <td>{{ $emp->phoneNumber }}</td>
                                    <td>{{ $emp->address }}</td>


                                    <td>
                                        {{--@if ( in_array($nam->isActive, array('Yes','No')) )--}}

                                        <div class="btn-group">
                                            <button type="button" class="btn btn-info">Action</button>
                                            <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
                                                <span class="caret"></span>
                                                <span class="sr-only">Toggle Dropdown</span>
                                            </button>
                                            <ul class="dropdown-menu" role="menu">
                                                {{--@if ($nam->isActive == 'Yes')--}}
                                                <li data-toggle="modal" data-target="#acceptModal" data-bookingid="{{ $emp->employeeID }}"><a href="{{ url('myform/edit/'.$emp->employeeID) }}">View/ Edit</a>
                                                </li>
                                                {{--@endif--}}
                                                <li><a href="{{ url('/myform/delete/'.$emp->employeeID)}}">Delete</a></li>
                                            </ul>
                                        </div>
                                        {{--@endif--}}
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                        {{$employer->links()}}
                    </div>
                </div>
            </div>
        </div>
    </div>


    {{--<a href="{{ url('user/add') }}"> <input type="submit" id="add" name="add" value="Edit" class="button"></a>--}}

    </br>




    <h4>Create a new Employee</h4>
    {{--<form class="templatemo-preferences-form" role="form" method="POST" action="{{ action('UserController@save') }}">--}}
    {{--<input type="hidden" name="_token" value="{{ csrf_token() }}">--}}

    <form role="form" method="POST" action="{{ url('myform/index') }}">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">


        <div class="row">
            <div class="col-md-6 margin-bottom-15">

                <input type="text" class="form-control" name="employeeID" value="{{ old('employeeID') }}" placeholder="Enter employee ID">
            </div>
            <div class="row templatemo-form-buttons">
                <div class="submit-button">
                    <button type="submit" class="btn btn-primary">New</button>

                </div>
            </div>
        </div>
    </form>
    {{--</form>--}}


    <script type="text/javascript">
        $(document).ready(function() {
            $('#example').dataTable();
        } );
    </script>


@endsection

"edit.blade.php" is “ edit.blade.php”是

 @extends('app')

@section('content')

    <div class="templatemo-content-wrapper">
        <div class="container">
            <ol class="breadcrumb">
                <li><a href="{{ url("/") }}"><font color="green">Home</font></a></li>
                <li class="active">Employee Form</li>
            </ol>
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <div class="panel panel-success">
                        <div class="panel-heading">Employee Form</div>
                        <div class="panel-body">
                            @if (count($errors) > 0)
                                <div class="alert alert-danger">
                                    <strong>Whoops!</strong> There were some problems with your input.<br><br>
                                    <ul>
                                        @foreach ($errors->all() as $error)
                                            <li>{{ $error }}</li>
                                        @endforeach
                                    </ul>
                                </div>
                            @endif

                            <form class="form-horizontal" role="form" method="POST" action="{{ url('myform/myform/') }}">
                                <input type="hidden" name="_token" value="{{ csrf_token() }}">
@foreach($user as $use)
                                <div class="form-group">
                                    <label class="col-md-4 control-label">Employee ID</label>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" name="employeeID" value="{{ $use->employeeID }}" placeholder="Enter employee ID">
                                    </div>
                                </div>


                                <div class="form-group">
                                    <label class="col-md-4 control-label">E_number</label>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" name="employeeNo" value="{{ $use->employeeNo}}" placeholder="Enter employee number">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-md-4 control-label">Name</label>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" name="Cname" value="{{ $use->Cname }}" placeholder="Enter Contact Name">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-md-4 control-label">DOB</label>
                                    <div class="col-md-6">
                                        <input type="date" class="form-control" name="dob" value="{{ $use->dob }}" placeholder="Enter date of birth">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-md-4 control-label">Contact Phone</label>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" name="phoneNumber" value="{{ $use->phoneNumber }}" placeholder="Enter Mobile Number">
                                    </div>
                                </div>



                                <div class="form-group">
                                    <label class="col-md-4 control-label">Address</label>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" name="address" value="{{ $use->address }}" placeholder="Enter Address">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <div class="col-md-6 col-md-offset-4">
                                        <button type="submit" class="btn btn-warning"><a href="{{ url('myform/update/'.$use->employeeID) }}">
                                            Update</a>
                                        </button>
                                    </div>
                                </div>

                                {{--<a href="{{ url('myform/index') }}"> <input type="button" id="add" name="add" value="View data" class="button"></a>--}}

    @endforeach
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

"myformController.php" is “ myformController.php”是

  <?php


namespace App\Http\Controllers;

use App\myform;
use Mail;
use Illuminate\Support\Facades\DB;
use Faker\Provider\DateTime;
use App\User;
use App\Http\Requests\createUserRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Symfony\Component\HttpFoundation\Request;

class myformController extends Controller
{
    public $type = 'myform';


    public function getIndex()
    {
//        $user = DB::table('user')->get();
        $employer = DB::table('employee')->simplePaginate(5);
        return view('myform.index')->with('employer',$employer);
    }


    public function formInsert()
    {
        $postform = Input::all();
        //insert data into mysql table
        $data =      array('employeeID'=> $postform['employeeID'],
            'employeeNo'=> $postform['employeeNo'],
            'Cname'=> $postform['Cname'],
            'dob'=> $postform['dob'],
            'phoneNumber'=> $postform['phoneNumber'],
            'address'=> $postform['address'],


        );
        //  echo print_r($data);
        $ck = 0;
        $ck = DB::table('employee')->Insert($data);
        //echo "Record Added Successfully!";
        $employer = DB::table('employee')->simplePaginate(10);
        return view('myform.index')->with('employer',$employer);


    }

    public function delete($id)
    {
        DB::table('employee')->where('employeeID', '=', $id)->delete();
        $employer = DB::table('employee')->simplePaginate(10);
        return view('myform.index')->with('employer', $employer);
    }

    public function formIDinsert()
    {
        $postform = Input::all();
        //insert data into mysql table
        $data =      array('employeeID'=> $postform['employeeID'],

        );
        //  echo print_r($data);
        $ck = 0;
        $ck = DB::table('employee')->Insert($data);
        //echo "Record Added Successfully!";
        $employer = DB::table('employee')->simplePaginate(10);
        return view('myform.index')->with('employer',$employer);


    }

    public function edit($id)
    {
        try {
            //Find the user object from model if it exists
          $user=DB::table('employee')->where('employeeID', '=', $id)->get();
            //$user = User::findOrFail($id);
            //Redirect to edit user form with the user info found above.
          return view('myform.edit')->with ('user', $user);

            //return view('myform.edit')->with('user', myform::find($id));
        } catch (ModelNotFoundException $err) {
            //redirect to your error page
        }
    }

    // Update user
    public function update(Request $request, $id)
    {
        try{
            //Find the user object from model if it exists
            $user= myform::findOrFail($id);
            DB::table('employee')
                ->where('employeeID', $id)
                ->update(['employeeNo' =>$request['employeeNo'],
                'Cname'=>$request['Cname'],
                'phoneNumber'=>$request['phoneNumber'],
                'address'=>$request['address']
                ]);
            //Set user object attributes
            //the $request index should match your form field ids!!!!!
            //you can exclude any field you want.

//            $user->employeeNo = $request['employeeNo'];
//            $user->Cname = $request['Cname'];
//            $user->phoneNumber = $request['phoneNumber'];
//            $user->address = $request['address'];

            //Save/update user.
            $user->save();
            return view('myform.index')->with('user', $user);
            //redirect to somewhere
        }
        catch(ModelNotFoundException $err){
            //Show error page
        }
    }


}

model "myform.php" is 模型“ myform.php”是

   <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class myform extends Model
{

    protected $table = 'employee';
    //protected $primaryKey = 'employeeID';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'employeeID',
        'employeeNo',
        'Cname',
        'dob',
        'phoneNumber',
        'address',

    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Routes.php is Routes.php是

    Route::any('myform', function()
{
    return view('myform/myform');
});

Route::any('myform/myform', 'myformController@formInsert');
Route::any('myform/index', 'myformController@getIndex');
//to show edit form and fetch passed user id info from db
Route::get('myform/edit/{id}', 'myformController@edit');

//to get the edited info and save it to db
Route::get('myform/update/{id}', 'UserController@update');
Route::any('myform/index', 'myformController@formIDinsert');
Route::any('myform/delete/{id}', 'myformController@delete');

You wanna change this in your route: 您想更改您的路线:

Route::get('myform/update/{id}', 'UserController@update');

to

//Because the data in your form is transferred/submitted by post request
Route::post('myform/update/{id}', 'UserController@update');

then change your update function to this 然后将您的更新功能更改为此

// Update user
public function update(Request $request, $id)
{
    try{
        //Find the user object from model if it exists
        $user= myform::findOrFail($id);

        //$request contain your post data sent from your edit from
        //$user is an object which contains the column names of your table

        //Set user object attributes
        $user->employeeNo = $request['employeeNo'];
        $user->Cname = $request['Cname'];
        $user->dob = $request['dob'];
        $user->phoneNumber = $request['phoneNumber'];
        $user->address = $request['address'];

        // Save/update user. 
        // This will will update your the row in ur db.
        $user->save();

        return view('myform.index')->with('user', $user);
    }
    catch(ModelNotFoundException $err){
        //Show error page
    }
}

If you have any question or need clarification you are most welcome to ask :) 如果您有任何疑问或需要澄清,欢迎您提出:)

Update in your edit view 在您的编辑视图中更新

change this 改变这个

<form class="form-horizontal" role="form" method="POST" action="{{ url('myform/myform/') }}">

to

<form class="form-horizontal" role="form" method="POST" action="{{ url('myform/update/').$user->employeeID}}">

change $user->employeeID to whatever is your primary key. $user->employeeID更改为您的主键。

Also change this 也改变这个

<button type="submit" class="btn btn-warning"><a href="{{ url('myform/update/'.$use->employeeID) }}">
                                        Update</a>
                                    </button>

to this 对此

<button type="submit" class="btn btn-warning">Update</button>

Aso you didn't fix your route as I mentioned earlier in this answer. 麻生太郎没有像我在此答案前面提到的那样修复路线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM