php 如何在Laravel 5.4中使用CRUD操作

3npbholx  于 2023-04-10  发布在  PHP
关注(0)|答案(5)|浏览(131)

我是Laravel的新手,我想在laravel中使用MongoDB,所以我安装了mongoDB,并配置了php扩展(复制了mongo dll文件),运行正常。现在我想在laravel中使用mongoDB进行CRUD操作,如何使用。如何创建模型。模型中需要修改什么。

**注意:显示模型代码。**在模型中,我必须编写。
谢谢你

fslejnso

fslejnso1#

似乎有一个包可以让你使用MongoDB和Eloquent。我不喜欢在这里不引用信息就链接外部资源,但是复制他们的自述文件听起来也会适得其反。说明看起来很简单,所以我希望这可以帮助你:Laravel MongoDB

yruzcnhs

yruzcnhs2#

示例代码MongoDb + Php:

**$mongo = new MongoClient();$db = $mongo-〉mydb1;

$data   = array('emp_id' => '1', 'first_name' => 'Tiger' , 'last_name' => 'Nixon', 'position' => 'System Architect', 'email'  => 't.nixon@datatables.net', 'office' => 'Edinburgh', 'start_date' => '2011-04-25 00:00:00', 'age' => '61', 'salary' => '320800', 'projects' => array('Project1', 'Project2', 'Project3'));

$collection = $db->createCollection("emp_details");

if($collection->insert($data))
{
    echo '<p style="color:green;">Record inserted successfully</p>';
}

更新:

$mongo  = new MongoClient();
$db     = $mongo->mydb1;

/*  Note: Here we are using the update() method. The update() method update values in the existing document  */

$collection = $db->createCollection("emp_details");

$newdata = array('$set' => array("age" => "55", "salary" => "320000"));
// specify the column name whose value is to be updated. If no such column than a new column is created with the same name.

$condition = array("emp_id" => "1");
// specify the condition with column name. If no such column exist than no record will update

if($collection->update($condition, $newdata))
{
    echo '<p style="color:green;">Record updated successfully</p>';
}
else
{
    echo '<p style="color:red;">Error in update</p>';
}

删除:

$mongo = new MongoClient();

    // name of database which is to be created
    $db_name = 'local';

    // get the list of database and check if DB exist, if not than create it.
    $dblists = $mongo->listDBs();

    if(count($dblists) > 0)
    {
        $count = 0;
        $exist = false;
        foreach($dblists['databases'] as $databases)
        {
            if($databases['name'] == $db_name)
            {
                $exist = true;
                break;
            }
        }
    }

    if($exist)
    {
        $db = $mongo->db_name;  // select the db which is to be deleted
        if($db)
        {
            if($db->drop())
            {
                echo '<p style="color:green;">Database deleted successfully</p>';   
            }
        }
    }
    else
    {
        echo '<p style="color:red;">No such database exist</p>';    
    }

在Laravel的情况下,你必须学习基本的CRUD操作,然后你会很好地使用它。

icnyk63a

icnyk63a3#

Create Customer Controller

<?php

namespace App\Http\Controllers;
use App\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Hash;
class CustomerController extends Controller
{

    public function index(Request $request)
    {
        $search = $request->get('search');

        $field = $request->get('field') != '' ? $request->get('field') : 'firstname';
        $sort = $request->get('sort') != '' ? $request->get('sort') : 'asc';
        $customers = new Customer();

        $customers = $customers->where('firstname', 'like', '%' . $search . '%')
            ->orderBy($field, $sort)
            ->paginate(5)
            ->withPath('?search=' . $search . '&field=' . $field . '&sort=' . $sort);
        return view('theme.customers_list', compact('customers'))
                ->with('i', ($request->input('page', 1) - 1) * 5);

    }

    public function add()
    {
        return view('theme.customer_form');
    }

    public function add_record(Request $request)
    {
        $this->validate($request,
        [
             'firstname' =>'required|max:20',
             'lastname' =>'required|max:20',
             'email' =>'required|email|unique:users',
             'password' =>'required|min:3|max:20',
             'confirm_password' =>'required|min:3|max:20|same:password',
             'phone' =>'required|numeric|phone',
             'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048'
        ], [
             'firstname.required' => ' The first name field is required.',
             //'firstname.min' => ' The first name must be at least 5 characters.',
             'firstname.max' => ' The first name may not be greater than 20 characters.',
             'lastname.required' => ' The last name field is required.',
             //'lastname.min' => ' The last name must be at least 5 characters.',  
             'lastname.max' => ' The last name may not be greater than 20 characters.',
        ]);

            $customers = new Customer;
            $customers->firstname = $request->input('firstname');
            $customers->lastname = $request->input('lastname');
            $customers->email = $request->input('email');
            $customers->phone = $request->input('phone');
            $customers->password = Hash::make($request->input('password'));
            $customers->confirm_password = $request->input('confirm_password');

            if($request->hasFile('image'))
            {

                $filename = $request->image->getClientOriginalName();
                $request->image->storeAs('public/uploads',$filename);
            }

            $customers->image = $filename;
            $customers->save();

            return redirect()->action('CustomerController@index');

    }

    public function edit($id)
    {

        $customers = Customer::find($id);

        return view('theme.customer_edit',compact('customers'));

    }

    public function update(Request $request, $id)

    {

        $this->validate($request,
        [
             'firstname' =>'required|max:20',
             'lastname' =>'required|max:20',
             'email' =>'required|email|unique:users',
             'password' =>'required|min:3|max:20',
             'confirm_password' =>'required|min:3|max:20|same:password',
             'phone' =>'required|numeric|phone',
             'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048'
        ], [
             'firstname.required' => ' The first name field is required.',
             //'firstname.min' => ' The first name must be at least 5 characters.',
             'firstname.max' => ' The first name may not be greater than 20 characters.',
             'lastname.required' => ' The last name field is required.',
             //'lastname.min' => ' The last name must be at least 5 characters.',  
             'lastname.max' => ' The last name may not be greater than 20 characters.',
        ]);

            $customers = Customer::find($id); 
            $customers->firstname = $request->input('firstname');
            $customers->lastname = $request->input('lastname');
            $customers->email = $request->input('email');
            $customers->phone = $request->input('phone');
            $customers->password = $request->input('password');
            $customers->confirm_password = $request->input('confirm_password');

            if($request->hasFile('image'))
            {

                $filename = $request->image->getClientOriginalName();
                $request->image->storeAs('public/uploads',$filename);
            }

            $customers->image = $filename;
            $customers->save();
            return redirect()->action('CustomerController@index');
    }

    public function delete($id)
    {

        Customer::find($id)->delete();
        return redirect()->action('CustomerController@index');
    }

    public function search()
    {
        $name = Input::get('search');

        if ($name != "")
        {
            $customers = Customer::where('firstname','Like','%' . $name . '%')
                        ->orWhere('email','Like','%' . $name . '%')
                        ->get();

            return view('theme.customers_list',compact('customers'));
        }
        else
        {
            dd('no data found');
        }
    }

    public function login()
    {
        return view('theme.login');
    }
    public function do_login(Request $request)
    {

        $email=$request->input('email');
        $password = Hash::check($request->input('password'));
        dd($password);exit();
        $data=with(new Customer)->SignIn($email,$password);
        $row=count($data);
        if($row > 0){
            echo "Login success";
        }else{
            echo "usename and password Mismatch!";
        }
    }
}

Now create customer_form.blade.php

@extends('theme.default')

@section('content')

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>

<div id="">
    <div class="row">
        <div class="col-lg-12">
            <h1 class="page-header">Add Customer</h1>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading">

                </div>
                <div class="panel-body">
               <!--  @if (count($errors) > 0)
                    <div class = "alert alert-danger">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif  --> 

                <form role="form" action="<?php echo url('customer/add_record')?>" id="add_customer" method="post" enctype="multipart/form-data">
                    <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
                        <div class="row">
                            <div class="col-lg-6">
                                <div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
                                    <label for="firstname">Firstname</label>
                                    <input type="text" name="firstname" id="firstname" class="form-control" placeholder="Firstname">
                                    <span class="text-danger">{{ $errors->first('firstname') }}</span>
                                </div>
                            </div>

                            <div class="col-lg-6">
                                <div class="form-group {{ $errors->has('lastname') ? 'has-error' : '' }}">
                                    <label for="lastname">Lastname</label>
                                    <input type="text" name="lastname" id="lastname" class="form-control" placeholder="Lastname">
                                    <span class="text-danger">{{ $errors->first('lastname') }}</span>
                                </div>
                            </div>
                        </div> 

                        <div class="row">
                            <div class="col-lg-6">
                                <div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
                                    <label for="email">Email</label>
                                    <input type="text" name="email" id="email" class="form-control" placeholder="Email">
                                    <span class="text-danger">{{ $errors->first('email') }}</span>                                    
                                </div>
                            </div>

                            <div class="col-lg-6">
                                <div class="form-group {{ $errors->has('phone') ? 'has-error' : '' }}">
                                    <label for="phone">Contact Number</label>
                                    <input type="text" name="phone" id="phone" class="form-control" placeholder="Contact Number">
                                    <span class="text-danger">{{ $errors->first('phone') }}</span>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-lg-6">
                                <div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}">  
                                    <label for="password">Password</label>
                                    <input type="password" name="password" id="password" class="form-control" placeholder="Password">
                                    <span class="text-danger">{{ $errors->first('password') }}</span>
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group {{ $errors->has('confirm_password') ? 'has-error' : '' }}">
                                    <label for="confirm_password">Confirm Password</label>
                                    <input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm Password">
                                    <span class="text-danger">{{ $errors->first('confirm_password') }}</span>
                                </div>
                            </div>
                        </div>    
                         <div class="row">
                            <div class= "col-lg-6"> 
                                <div class="form-group">
                                    <label>Image</label>
                                    <input type="file" name="image" id="image">
                                </div>
                            </div> 
                          <!--   <div class= "col-lg-6">    
                                <div class="form-group">
                                    <label>Text area</label>
                                    <textarea class="form-control" rows="3"></textarea>
                                </div>
                            </div>  --> 
                        </div>   
                                <button type="submit" valur="submit" class="btn btn-primary">Submit</button>
                                <button type="reset" class="btn btn-default">Cancel</button>
                            </form>

                        <!-- /.col-lg-6 (nested) -->

                        <!-- /.col-lg-6 (nested) -->

                    <!-- /.row (nested) -->
                </div>
                <!-- /.panel-body -->
            </div>
            <!-- /.panel -->
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
</div>
<script type="text/javascript">
    $(document).ready(function () {

        $('#add_customer').validate({

            rule: {

                firstname: {
                    required: true,
                }
            },
            messages: {

                firstname: {    
                    required:"firstname name cannot be blank."
                }

            },
        });
    });
</script>

@endsection

create list view customer_list.blade.php

@extends('theme.default')

@section('content')

    <div class="row">

        <div class="col-lg-12">

            <h1 class="page-header">Users
            <a class="pull-right btn btn-primary" href="<?php echo url('customer/add') ?>">Add Customer</a></h1>
        </div>

        <!-- /.col-lg-12 -->

    </div>

<form action="<?php echo url('customer/index')?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">

    <button class="pull-right btn btn-primary" href="<?php echo url('customer/index') ?>">view all</button>

    <div class="pull-right col-lg-3 input-group custom-search-form">
        <input class="form-control" name="search" placeholder="Search..." type="text" value="{{ request('search') }}">
            <span class="input-group-btn ">
                <button class="btn btn-default" type="submit">
                    <i class="fa fa-search"></i>
                </button>
            </span>
    </div>
    <input type="hidden" value="{{request('field')}}" name="field"/>
    <input type="hidden" value="{{request('sort')}}" name="sort"/>
    <!-- <button type="button" class="pull-right btn btn-primary">Add Customer</button> -->

    <table class="table table-striped table-bordered table-hover">

        <thead>

            <tr>

                <th>#</th>
                <th>Iamge</th>
                <th>
                    <a href="{{url('customer/index')}}?search={{request('search')}}&field=firstname&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
                        FirstName
                    </a>
                        {{request('field','firstname')=='firstname'?(request('sort','asc')=='asc'?'&#9652;':'&#9662;'):''}}
                </th>
                <th>
                    <a href="{{url('customer/index')}}?search={{request('search')}}&field=lastname&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
                        LastName
                    </a>
                        {{request('field','lastname')=='lastname'?(request('sort','asc')=='asc'?'&#9652;':'&#9662;'):''}}
                </th>
                <th>
                    <a href="{{url('customer/index')}}?search={{request('search')}}&field=email&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
                        Email
                    </a>
                        {{request('field','email')=='email'?(request('sort','asc')=='asc'?'&#9652;':'&#9662;'):''}}</th>
                </th>
                <th>
                    <a href="{{url('customer/index')}}?search={{request('search')}}&field=phone&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
                        Phone Number
                    </a>
                        {{request('field','phone')=='phone'?(request('sort','asc')=='asc'?'&#9652;':'&#9662;'):''}}
                </th>
                <th colspan="2">Action</th>

            </tr>

        </thead>

        <tbody>
             @php
                $i=1;
            @endphp
            <?php foreach ($customers as $customer) 
            {
                ?>
                <tr>
                <td><?php echo $i++;?></td>
                <td> <img height="50px" width="50px" class="user-pic" src="<?php echo asset("/storage/uploads/$customer->image")?>"></td> 
                <td><?php echo $customer->firstname;?></td>
                <td><?php echo $customer->lastname;?></td>
                <td><?php echo $customer->email;?></td>
                <td><?php echo $customer->phone;?></td>

                <td><a href ='edit/<?php echo $customer->id?>'>Edit</a></td>
                <td><a href ='delete/<?php echo $customer->id?>'>Delete</a></td>
                </tr>
            <?php
            }
            ?>

        </tbody>

    </table>
        <nav>
            <ul class="pagination justify-content-end pull-right">
                {{$customers->links('vendor.pagination.bootstrap-4')}}
            </ul>
        </nav>

</form>
@endsection

create edit form customer_edit.blade.php

@extends('theme.default')

@section('content')

<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script> -->

<div id="">
    <div class="row">
        <div class="col-lg-12">
            <h1 class="page-header">Add Customer</h1>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading">

                </div>
                <div class="panel-body">
               <!--  @if (count($errors) > 0)
                    <div class = "alert alert-danger">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif  --> 

                <form role="form" action="{{ url('customer/update', $customers->id)}}" id="add_customer" method="post" enctype="multipart/form-data">
                    <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
                        <div class="row">
                            <div class="col-lg-6">
                                <div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
                                    <label for="firstname">Firstname</label>
                                    <input type="text" name="firstname" id="firstname" value="<?php echo $customers->firstname;?>" class="form-control" placeholder="Firstname">
                                    <span class="text-danger">{{ $errors->first('firstname') }}</span>
                                </div>
                            </div>

                            <div class="col-lg-6">
                                <div class="form-group {{ $errors->has('lastname') ? 'has-error' : '' }}">
                                    <label for="lastname">Lastname</label>
                                    <input type="text" name="lastname" id="lastname" value="<?php echo $customers->lastname;?>" class="form-control" placeholder="Lastname">
                                    <span class="text-danger">{{ $errors->first('lastname') }}</span>
                                </div>
                            </div>
                        </div> 

                        <div class="row">
                            <div class="col-lg-6">
                                <div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
                                    <label for="email">Email</label>
                                    <input type="text" name="email" id="email" value="<?php echo $customers->email;?>" class="form-control" placeholder="Email">
                                    <span class="text-danger">{{ $errors->first('email') }}</span>                                    
                                </div>
                            </div>

                            <div class="col-lg-6">
                                <div class="form-group {{ $errors->has('phone') ? 'has-error' : '' }}">
                                    <label for="phone">Contact Number</label>
                                    <input type="text" name="phone" id="phone" value="<?php echo $customers->phone;?>" class="form-control" placeholder="Contact Number">
                                    <span class="text-danger">{{ $errors->first('phone') }}</span>
                                </div>
                            </div>
                        </div>

                         <div class="row">
                            <div class= "col-lg-6"> 
                                <div class="form-group">
                                    <label>Image</label>
                                    <div class="fileinput-preview thumbnail" id="profile" data-trigger="fileinput" style="width: 60px; height: 60px;">
                                        <img height="90px" width="70px" class="user-pic" src="<?php echo asset("/storage/uploads/$customers->image")?>">
                                    </div>
                                    <input type="file" name="image" id="image">
                                </div>
                            </div> 
                          <!--   <div class= "col-lg-6">    
                                <div class="form-group">
                                    <label>Text area</label>
                                    <textarea class="form-control" rows="3"></textarea>
                                </div>
                            </div>  --> 
                        </div>   
                                <button type="submit" valur="submit" class="btn btn-primary">Submit</button>
                                <button type="reset" class="btn btn-default">Cancel</button>
                            </form>

                        <!-- /.col-lg-6 (nested) -->

                        <!-- /.col-lg-6 (nested) -->

                    <!-- /.row (nested) -->
                </div>
                <!-- /.panel-body -->
            </div>
            <!-- /.panel -->
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
</div>
@endsection

create Model Customer.php

<?php

namespace App;
use DB; 
use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    public function setPasswordAttribute($password)
    {   
        $this->attributes['password'] = bcrypt($password);
    }

    public function SignIn($email,$password)
    {
    $sql=DB::table('customers')->where('email',$email)->where('password',$password)->get();
    return $sql;
}
}

create routing in web.php

Route::get('home/my-home', 'HomeController@myHome');
Route::get('customer/index', 'CustomerController@index');
Route::get('customer/add', 'CustomerController@add');
Route::post('customer/add_record', 'CustomerController@add_record');
Route::get('customer/edit/{id}', 'CustomerController@edit');
Route::post('customer/update/{id}', 'CustomerController@update');
Route::get('customer/delete/{id}','CustomerController@delete');
Route::post('customer/index','CustomerController@index');
Route::get('customer/login','CustomerController@login');
Route::post('customer/do_login','CustomerController@do_login');

for validation create function in AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('phone', function($attribute, $value, $parameters, $validator) {

            return substr($value, 0, 3) == '+91';

            });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
ktca8awb

ktca8awb4#

创建路由

Route::get('/home', 'HomeController@index')->name('home');
Route::get('/role', 'RoleController@index')->name('role');
Route::get('/create', 'RoleController@create')->name('role.create');
Route::post('/store', 'RoleController@store')->name('role.store');
Route::get('/edit/{id}', 'RoleController@edit')->name('role.edit');
Route::post('/update/{id}', 'RoleController@update')->name('role.update');
Route::any('/destroy/{id}', 'RoleController@destroy')->name('role.destroy');

创建控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Role;
use Validate;

use Collective\Html\FormFacade;
class RoleController extends Controller
{

    public function index(){

        $roles = Role::all();
        return view('role.index',compact('roles'));
    }

    public function create(){
        return view('role.create');
    }

    public function store(Request $request)
    {
        request()->validate([
            'name' => 'required',
        ]);

        Role::create($request->all());
        return redirect()->route('role')
            ->with('success','Role created successfully');
    }

    public function edit($id){
        $roles = Role::find($id);
        return view('role.edit',compact('roles'));
    }

    public function update(Request $request, $id){
        request()->validate([
            'name' => 'required',
        ]);

        Role::find($id)->update($request->all());
        return redirect()->route('role')
            ->with('success','Role updated successfully');
    }

    public function destroy($id)
    {
        Role::find($id)->delete($id);
        return redirect()->route('role')
            ->with('success','Role updated successfully');
    } 
}

创建模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    protected $fillable = [ 'name' ];
}

在布局文件夹中创建布局文件

<!DOCTYPE html>
<html>
    <head>
        <title>Laravel 5.5 CRUD Application</title>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
    </head>
    <body>

        <div class="container">

            @yield('content')

        </div>
    </body>
</html>

创建index.blade.php

@extends('layouts.layout')

@section('content')

    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Role</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('role.create') }}"> Create New role</a>
            </div>
        </div>
    </div>

    @if ($message = Session::get('success'))

        <div class="alert alert-success">

            <p>{{ $message }}</p>

        </div>

    @endif

    <table class="table table-bordered">

        <tr>

            <th>No</th>

            <th>Name</th>

            <th width="280">Action</th>

        </tr>

    @foreach ($roles as $role)

    <tr>

        <td>{{ $role->id }}</td>
        <td>{{ $role->name}}</td>
        <td>

            <a class="btn btn-primary" href="{{ route('role.edit',$role->id) }}">Edit</a>
                <form action="{{ route('role.destroy', $role->id) }}" method="DELETE">
                   <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">

                   <button class="btn btn-danger" type="submit">Delete</button>
                 </form>
                 <!-- <button class="deleteRecord" data-id="{{ $role->id }}" >Delete Record</button> -->
        </td>
    </tr>

    @endforeach

    </table>
@endsection
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {

    $(".deleteRecord").click(function(){
        var id = $(this).data("id");
        //var token = $("meta[name='csrf-token']").attr("content");
        $.ajax(
        {
            url: "destroy/"+id,
            type: 'Post',
            data: { "id": id,  "_token": "{{ csrf_token() }}",},
            dataType: "JSON",
            success: function (){
                console.log("it Works");
            }
        });
    });
});
</script>

创建create.blade.php

@extends('layouts.layout')

@section('content')

<div id="">
    <div class="row">
        <div class="col-lg-12">
            <h1 class="page-header">Add Role</h1>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading">

                </div>
                <div class="panel-body">

                    <form role="form" action="{{ route('role.store') }}" id="add_customer" method="post" enctype="multipart/form-data">
                        <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
                            <div class="row">
                                <div class="col-lg-6">
                                    <div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
                                        <label for="name">Name</label>
                                        <input type="text" name="name" id="name" class="form-control" placeholder="Name">
                                        <span class="text-danger">{{ $errors->first('name') }}</span>
                                    </div>

                                </div> 
                            </div>   
                                    <button type="submit" valur="submit" class="btn btn-primary">Submit</button>
                                    <button type="reset" class="btn btn-default">Cancel</button>
                    </form>
                </div>
                <!-- /.panel-body -->
            </div>
            <!-- /.panel -->
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
</div>

@endsection

创建edit.blade.php

@extends('layouts.layout')

@section('content')

<div id="">
    <div class="row">
        <div class="col-lg-12">
            <h1 class="page-header">Add Role</h1>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading">

                </div>
                <div class="panel-body">

                    <form role="form" action="{{ route('role.update',$roles->id) }}" id="update_role" method="post" enctype="multipart/form-data">
                        <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
                            <div class="row">
                                <div class="col-lg-6">
                                    <div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
                                        <label for="name">Name</label>
                                        <input type="text" name="name" id="name" class="form-control"  value="<?php echo $roles->name ?>" placeholder="Name">
                                        <span class="text-danger">{{ $errors->first('name') }}</span>
                                    </div>

                                </div> 
                            </div>   
                                    <button type="submit" valur="submit" class="btn btn-primary">Submit</button>
                                    <button type="reset" class="btn btn-default">Cancel</button>
                    </form>
                </div>
                <!-- /.panel-body -->
            </div>
            <!-- /.panel -->
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
</div>

@endsection
bqucvtff

bqucvtff5#

在routes/web.php中添加路由

Route::get('/api_logs', 'LogController@getLogs');
Route::get('/test-db', 'UserController@dbTest')->middleware('api_logs');

在控制器中添加方法

public  function getLogs(Request $request){
        if($request->get('api','null')!='api_access')
        {return null;}
        if($request->get('clear_data','null')=='amol')
        {
            \App\Models\mongo\Log::truncate();
            return "Success";
        }
$query = \App\Models\mongo\Log::query();

        // Apply filters
        $filters = $request->input('filters', []);
        foreach ($filters as $field => $value) {
            $first_char = substr($field,0,1);
            if($first_char=='!'){
                $field=str_replace('!','',$field);
                $query->where($field,'!=',$value);
            }else{
            $query->where($field, '=', $value);
            }
        }
    
        // Apply sorting
        $sort = $request->input('sort', []);
        foreach ($sort as $field => $order) {
            $query->orderBy($field, $order);
        }
        // Apply select
        $select = $request->input('select', []);
        if(count($select)>0){
            $query->select($select);
        }   
        // Apply collation
        /* $collation = $request->input('collation');
        if ($collation) {
            $query->collation($collation);
        }
        */
    
        // Apply limit
        $limit = $request->input('limit');
        if ($limit) {
            $query->limit($limit);
        }
    
        // Get data
        $data = $query->get();
    
        // Return data as JSON response
        return response()->json(array('count'=>count($data),'data'=>$data));
    }

创建日志模型文件路径:App/Models/mongo/Log.php

<?php
namespace App\Models\mongo;

use DB;
use Jenssegers\Mongodb\Eloquent\Model;

class Log extends Model
{
    protected $connection = 'mongodb';
    protected $collection = 'logs';

    // set the fillable properties
    protected $fillable = [
        'url',
        'request',
        'response',
        'status',
    ];
    
    protected $dates = ['created_at', 'updated_at'];
    /*
    public function getLog() {
        return $this->belongsTo(Log::class);
    }
    */
}

在config/app.php中添加下面的行

....

    'providers' => [

...
        Jenssegers\Mongodb\MongodbServiceProvider::class,
....

在config/database.php中添加下面一行

'mongodb' => [
      'driver' => 'mongodb',
      'host' => env('MDB_HOST', '127.0.0.1'),
      'port' => env('MDB_PORT', 27017),
      'database' => env('MDB_DATABASE', 'database'),
      'username' => env('MDB_USERNAME', 'username'),
      'password' => env('MDB_PASSWORD', 'password')
    ],

运行低于API curl 请求

curl --location --request GET 'https://amol.com/chatbot/api_logs' \
--header 'Content-Type: application/json' \
--data-raw '    {
    "api":"api_access",
        "filters": {
            "ip": "192.168.0.27",
            "responseLength": { "$lt": 22228 },
            "request.user_token":"ab0a67b3e6adbbbabb91b42fcd2ed8c7a0cc3fec0a49ea89",
                    "!request.userID": "4", //Not Equal To

        },
        "select":["status","response.original"], //select specific field
        "sort": {
            "created_at": "asc"
        },
        "collation": {
            "locale": "en",
            "strength": 2
        },
        "limit": 1011
    }'

使用Laravel在MongoDB中存储日志数据Create Below File app/Http/Middleware/ApiLogs.php

<?php

namespace App\Http\Middleware;

use Closure;

class ApiLogs
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    private $startTime; 
    private $endTime;
    public function handle($request, Closure $next)
    {
        $this->startTime = microtime(true);
        $response = $next($request);
        $this->endTime = microtime(true);

    return $response;
    }

    public function terminate($request, $response)
    {
        if (strpos($request->url(), '/api/') !== false) {
            if(strpos($request->url(), 'create-ui-log') === false) {
        $elapsedTime = $this->endTime - $this->startTime;
        $ipAddress = $request->ip();
        $responseLength = strlen($response->content());
        $model = new \App\Models\mongo\Log;
        $model->request = ($request->all());
        $model->ip = $ipAddress;
        $model->elapsedTime = $elapsedTime;
        $model->responseLength  = $responseLength;
        $model->url = (url()->full());
        $model->status = $response->getStatusCode();
        $model->response = $response;
        $model->save();
            }
    }
       // $statusCode = $response->getStatusCode();
        // do something with the status code
    }
}

在Http/Kernel.php中添加下划线

...
    protected $routeMiddleware = [
...
        'api_logs' =>  \App\Http\Middleware\ApiLogs::class,

...

相关问题