dimanche 30 octobre 2016

MethodNotAllowedHttpException in RouteCollection.php line 218 Laravel 5.1 using Knockout js and Ajax

Hi there I´m new in this community. I´m developing a web application with Laravel 5.1, and I want to call the method store of my model Sale from an ajax POST request, but I have this from console:

MethodNotAllowedHttpException in RouteCollection.php line 218

What could it be? thanks a lot.

these are my routes:

//Rutas para inicios de sesión
Route::resource('log', 'LogController');
Route::get('logout','LogController@logout');

//Rutas generales
Route::get('/', 'WelcomeController@index');
Route::get('index', 'WelcomeController@indexdos');


//Routes for users
Route::get('user/actualizar','UserController@actualizar');
Route::get('user/deleter','UserController@deleter');
Route::resource('user', 'UserController');

//Routes for pacients
Route::get('pacient/deleter','PacientController@deleter');
Route::get('pacient/actualizar','PacientController@actualizar');
Route::resource('pacient', 'PacientController');

//Routes for medicaments
Route::get('medicament/deleter','MedicamentController@deleter');
Route::get('medicament/actualizar','MedicamentController@actualizar');
Route::resource('medicament', 'MedicamentController');

//Routes for doctors
Route::get('doctor/deleter','DoctorController@deleter');
Route::get('doctor/actualizar','DoctorController@actualizar');
Route::resource('doctor', 'DoctorController');

//Routes for dates
Route::get('date/deleter','DateController@deleter');
Route::get('date/actualizar','DateController@actualizar');
Route::get('date/bitacora','DateController@bitacora');
Route::resource('date', 'DateController');

//Routes for sales
Route::resource('sale', 'SalesController');`

This is the form that contents the values I want to send to sale.store

@extends('layouts.principal')
@include('Ventas.forms.barra')
@section('content')
<div class="container">
  {!!Form::open()!!}
     <input type="hidden" name="_token" value=""      id="token"></input>
    @include('Ventas.forms.sale')
    <button id="btnAgregar" data-bind="click: $root.agregarVenta"    class="btn btn-success">Registrar venta</button>
{!!Form::close()!!}
 </div>
@stop

As You can see, I include the 'sale' form, where I include knockout js code:

<div class="form-group">
<table>
<tr>
<td>{!!Form::label('id_doctor_1','Cita a la cual se facturará: ')!!}</td>
<td><select data-bind="options: $root.citas, optionsText: function(item) {
                   return item.paciente()  + '  (Fecha: ' + item.fecha() + ' , Hora: ' +item.hora() + ')'
               },
                                 value: selectedDate,
               optionsCaption: 'Elija una cita...'"></select></td>
</tr>
<tr>
  <td>{!!Form::label('Producto:')!!}</td>
  <td><select data-bind="options: $root.productos, optionsText: function(item) {
                                     return item.nombre()  + '  (Precio de venta: ' + item.precio_venta() + ' ,Existencias: ' +item.existencias() + ')'
                             },
                             value: selectedProduct,
                             optionsCaption: 'Elija un producto...'">     </select></td>

 <tr>
   <td>{!!Form::label('cantidad:')!!}</td>
 <td><input type="number" data-bind="value: cantidad"></input></td>
 </tr>
</table>
</div>
<div class="form-group">
  <label for="btnAgregar" class="col-sm-2 control-label"></label>
   <div class="col-sm-10">
     <button id="btnAgregar" data-bind="click: $root.agregarProducto_venta"   class="btn btn-primary col-sm-8 col-md-offset-1">Agregar producto a la venta actual</button>
</div>
</div>

<div class="form-group">
<br><br/><br><br/>
</div>

<div data-bind="visible: selectedDate"> <!-- Appears when you select something -->
 <div class="post format-image box masonry-brick">
 <!-- Begin Blog Grid -->
 <div class="blog-wrap">
  <table>
     <tr>
         <td><strong>Detalles de cita elegida</strong></td>
     </tr>
     <tr>
         <td><strong>Paciente:</strong></td>
         <td><span data-bind="text: selectedDate() ? selectedDate().paciente : 'unknown'"></span></td>
     </tr>
     <tr>
         <td><strong>Producto:</strong></td>
         <td><span data-bind="text: selectedDate() ? selectedDate().producto : 'unknown'"></span></td>
     </tr>
     <tr>
         <td><strong>Cantidad:</strong></td>
         <td><span data-bind="text: selectedDate() ? selectedDate().cantidad : 'unknown'"></span></td>
     </tr>
     <tr>
         <td><strong>Subtotal:</strong></td>
         <td><span data-bind="text: selectedDate() ? selectedDate().subtotal : 'unknown'"></span></td>
     </tr>
     <tr>
         <td><br><br></td>
     </tr>
     <tr>
         <td><strong>Productos a facturar</strong></td>
     </tr>
     <tr>
         <td colspan="2"></td>
     </tr>
 </table>
 <table>
         <thead>
                 <tr><th>Nombre del producto____|</th><th>Precio____|</th><th>Cantidad____|</th><th>Subtotal____|</th><th>Acción____|</th></tr>
         </thead>
         <tbody data-bind="foreach: productos_venta">
                 <tr>
                         <td data-bind="text: producto"></td>
                         <td data-bind="text: precio"></td>
                         <td data-bind="text: cantidad"></td>
                         <td data-bind="text: subtotal"></td>
                         <td><a href="#" data-bind="click: $root.removeProduct">Remover</a></td>
                 </tr>
         </tbody>
 </table>
  </div>
    </div>
</div>
<h3 style="color:#FAFAFA" data-bind="visible: totalSurcharge() > 0">
  Total (incluyendo medicamentos y cita): $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
</h3>

And finally this is my app.js file, It is supposed that when I click on the button btnAgregar, the method agregarVenta makes an ajax request type POST, but it doesn´t work, what am I doing wrong? Again, thanks a lot.

File app.js (ajax method):

//Método para agregar una nueva venta al arreglo de ventas, y después pasarlo
//a la base de datos.
self.agregarVenta=function(){
  // crea un nuevo objeto Venta y después lo añade al arreglo.
  var id_cita = self.selectedDate().id();
    var venta= new Venta({id_cita: id_cita,producto:   self.selectedDate().producto(),
    cantidad: self.selectedDate().cantidad(),subtotal:  self.selectedDate().subtotal()});
    self.ventas().push(venta);

  for (var i = 0; i < self.productos_venta().length; i++) {
    venta= new Venta({id_cita: id_cita,producto: self.productos_venta()[i].producto(),
      cantidad: self.productos_venta()[i].cantidad(),subtotal: self.productos_venta()[i].subtotal()});
        self.ventas().push(venta);
  }
  var token = $("#token").val();
  var ruta = "sale.store"
  $.ajax({
     route: ruta,
     headers: {'X-CSRF-TOKEN': token},
     type: 'POST',
     data: {ventas: self.ventas()},
     dataType: 'JSON',
     error: function(respuesta) {alert("error");},
     success: function(respuesta) {
       if (respuesta) {
         alert("exito");
       }else {
         alert("error");
       }
     }
 });
 }
}



via Chebli Mohamed

jeudi 27 octobre 2016

Codeception Laravel5 Module Cleanup

I have been using Codeception 2.1.2 with the Db module to test my Laravel 5.1.35 for a while, using the Db module to handle database cleanup between tests. Because I have a significant amount of data setup that needs to occur, as the test suite has grown our tests have slowed down significantly.

I have recently upgraded to Codeception 2.2.6 and all tests work as I would expect. When I then remove the Db Module in favor of the Laravel5 module, tests run faster but get gradually slower and slower over the duration of the suite, where tests that take a second or two in isolation, may take upwards of minutes to complete when running the full suite.

It seems like there's a memory leak somewhere, either in my code or in the Laravel5 module itself, but it is incredibly difficult to pinpoint. I've tried removed all DB transactions in code to see if nested transactions were the cause, different versions of Codeception, different cleanup methods, like not using Laravel5 to clean up, but rather using a Seeder to clean up transactional data but have had no luck.

Any ideas or thoughts would be greatly appreciated.



via Chebli Mohamed

mercredi 26 octobre 2016

Acessing $this from within an eloquent relationship

I have a property model that looks something like this:

class Property extends Model
{
    public function accessUsers()
    {
        $access_id = $this->access_id

        return $this->hasMany('App\User')
            ->whereHas('access', function ($query) use ($access_id) {
                $query->where('id', $access_id);
            });
    }
}

To be clear: A Property has many Users. Users has a relationship to a model called Access. This query should only result with users who have a reltionship with Access where Access.id is equal to Property.access_id

The problem I'm running into is when $this->access_id is called it's returning a null value (even when a value exists). dd($this) returns a Property object but with the attributes all empty. I'm inclined to belive that at this point of the code Eloquent/QueryBuilder hasn't queried the DB to retrieve the attribute values yet.

Is it possible to pull in the values at this point? Can I structure this in a different way that will give me the same results? I'd like to eager load these accessUsers() from a controller like so: Property::with('accessUsers')->get()



via Chebli Mohamed

Laravel ulr in search engines have index.php

How can I hide index.php in search engines, I think this is my Htaccess Problem, But I dont Know how to fix this . look at this picture please.

enter image description here



via Chebli Mohamed

Create a Laravel Request object on the fly

I'm handling data in one controller and want to pass it further into another controller to avoid duplicate code.

Is there a way to set up a Request object that is needed in the other controller's store-method? I've traced down the Request inheritance and came to Symfony's Request object which has a request property that is in fact a ParameterBag that holds a method add to add parameters with values to it.

I've tried the following but I'm getting null as result:

$myRequest = new Request();
$myRequest->request->add(['foo' => 'bar']);
var_dump($myRequest->foo);

I'm on Laravel 5.1 for this project.



via Chebli Mohamed

File Data is blank array in server side: Laravel 5.3

I am trying to post File using JQuery. Below is my code.

<script language="javascript">
    $(document).ready(function() {
        $('#frmUpdateProfile').on("submit", function(event) {
            event.stopPropagation(); // Stop stuff happening
            event.preventDefault(); // Totally stop stuff happening
            var data = {
                "FileName"      :   event.target.FileName.files,
                "_token"        :   "{!! csrf_token() !!}"
            };
            $.ajax({
                url:            '',
                method:         "POST",
                async:          true,
                data:           JSON.stringify(data),
                processData:    false,
                contentType:    "application/json; charset=utf-8",
                success: function (msg) {
                    SuccessCallback(msg);
                },
                error: function (jqXHR) {
                    ErrorCallback(jqXHR);
                }
            });
        });
    });
</script>

I tried processData: false,. While debugging in Js, you can check that image is coming in the data. Below is the screenshot.

enter image description here

But when I print the request data in Laravel, it show blank array.

Html form is here

<form method="POST" 
        action="http://localhost:1234/AS6-Code/public/UpdateProfile" 
        accept-charset="UTF-8" 
        enctype="multipart/form-data"  
        id="frmUpdateProfile">

    <input name="_token" type="hidden" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
    <input type="hidden" name="_token" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
    <input multiple="1" name="FileName" type="file">
    <input class="btn btn-info" type="submit" value="Update">
</form>

Am I doing something wrong?



via Chebli Mohamed

jquery ajax post request to remote server not ending - pending

jquery ajax post request with large text ( 14,4,Kb ) pending on net server.

If the data is less than 1240 bytes ( with id and identifikator 1253 bytes) then works.

Not work only on my computer. Even from Virtual Mashine ( Win10 ). On other computer works fine. On local server works fine.

Linux Mint 17.3
nginx/1.4.6 (Ubuntu)
php 5.5.9-1ubuntu4.20
laravel 5.1 
jquery 2.2.3

You have any idea why?



via Chebli Mohamed