简体   繁体   中英

When to write stored procedures in laravel 5.x

I know it is some where not related to a particular bug. But I am eager to know when should I use stored procedures in laravel ? I read couples of articles. Here below is the summary. According to this article Advantages and Drawbacks of Using Stored Procedures for Processing Data these procedures are having pros and cons. No doubt using stored procedures will enhance speed ( Sorry for my lack of knowledge ) but one thing hit in my mind and that is :

Alternatives to Stored Procedures

Here are the two alternatives

  1. In-line or Parameterized Queries
  2. Object Relational Mapping (ORM)

Some how I got to know that LARAVEL is having finest Abstract DB use and no doubt I am not good enough in writing stored procedures. Can anyone suggest me whether I need to write stored procedures or not ? If yes then when ??

Here is the text of above article

Stored Procedures may not always be the right answer for processing data, but there's also not enough compelling evidence to not use them either. Whether or not to use them determines on your particular situation and ability to develop the Stored Procedure(s) to match. Just like with writing a good, quality application, if you or your developers can write good, quality Stored Procedures, then by all means implement them. If they can't, then another solution might be best for you.

Any guidance will help me a lot. :)

Stick with laravels default eloquent ORM. If you find that you need functionality that you cannot obtain using an active record pattern, look into doctrine. I wouldn't use stored procedures unless you have a particularly complex query that you want to be compiled on your database server for performance reasons.

Premature optimization is a project killer.

This may help you a bit , this is a long ago answer for executing stored procedures in laravel 4

based on this answer I've created a example to execute stored procedure on laravel 5

This includes a model, a view and and stored procedure call included in routes.php file using DB:: class in laravel.

Route routes.php

<?php
use App\Document;
use Illuminate\Support\Facades\Input;

Route::group(['middleware' => ['web']], function () 
{
    Route::get('documents/send',function()
    {
         return view('documents/create');  
    });

    Route::post('documents/add',function(\Illuminate\Http\Request $request)
    { 
     if(isset($request['name']) && ($request['path']))
     {
          $doc_name = Input::get('name');
          $doc_path = Input::get('path');
          return DB::select('call sp_insert_document_details(?,?)',array($doc_name,$doc_path));

     }
     return redirect()->back();
    });
});

The model Document.php

<?php

namespace App;

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

class Document extends Model
{
   protected $table = 'document_details';
   protected $fillable = ['document_name','document_path'];
}

and lastly the view create.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Main template</title>

  <link href="{{asset('css/bootstrap.css')}}" rel="stylesheet">
  <link href="{{asset('css/lato.css')}}" rel="stylesheet">
  <script src="{{asset('js/jquery.js')}}"></script>

  <style>
      body { font-family: 'Calibri'; }
  </style>
<head/>
<body>
 <div class="panel panel-primary"> 
  <div class="panel-heading">Stored Procedures Panel</div>  
  <div class="panel-body">
  @if (session()->has('success'))
    <div class="alert alert-success" role="alert">{{ session('success') }}   </div>
  @endif   
    <form method="POST" action="add" class="form-horizontal panel">
      {!! csrf_field() !!}
      <div class="form-group ">
        <label for="name" class="col-md-4 control-label">Document name:</label>
        <div class="col-md-6">
          <input class="form-control" name="name" type="text" id="name" value="">
        </div>
        <label for="name" class="col-md-4 control-label">Document path:</label>
        <div class="col-md-6">
          <input class="form-control" name="path" type="text" id="path" value="">
        </div> 
        <div class="col-md-6 col-md-offset-4">
            <button type="submit" class="btn btn-success">Send Data</button>
        </div>
        <div class="col-md-6 col-md-offset-4">
            <input type="hidden" value="{{ Session::token()}}" name="_token">
        </div>
      </div>
    </form>
  </div>        
 </div>
</body>
</html>

The mysql db and table create commands (insert these lines in mysql console in windows or linux environment)

   mysql>create schema nerds;
   mysql>use nerds;
   Database changed
   mysql>CREATE TABLE document_details (
       ->id int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
       ->document_name VARCHAR(100) NOT NULL,
       ->document_path VARCHAR(100) NOT NULL);

The mysql stored procedure (insert these lines in mysql console in windows or linux environment)

   mysql>DELIMITER//
   mysql>CREATE PROCEDURE sp_insert_document_details
       ->(IN name VARCHAR(100), IN path VARCHAR(100) )
       ->BEGIN
       ->INSERT INTO document_details(document_name,document_path) VALUES(name,path);
       ->END//
   mysql>DELIMITER;

This is worked well and has speed execution than mysql queries

below is the link for the whole example.

this is not met with active records , but hope this example will help you as a working example!

The performance of stored function vs standard mysql query 存储函数与标准mysql查询的性能

extracted from the book "MYSQL stored procedure programming"

Stored procedure is a generic program unit have the ability of execution on request that can accept multiple input and output parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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