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

Flash alerts multiple times laravel

Flash alerts multiple times laravel even after remove from session here is my code http://kopy.io/CPwkR



via Chebli Mohamed

mardi 25 octobre 2016

Don't work laravel $request

Ajax response!

Don't work:

$request->input('fio');
$request->fio;

Worked only

$request->all();

But i need to access single values.

Object {
    fio: "Illya Yaremchuk",
    email: "zzzzz@sssss.com",
    _token: "A4bGMcklDoj4VrMzFk0qIKtVlYuX5U9o" }



via Chebli Mohamed

Laravel - Many to Many - Model binding

I need some help.

I have these tables: users, buys and codecs. I have a many-to-many relationship: buys, codecs, buy_codec

Tables

Schema::create('codecs', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});

Schema::create('buys', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->string('name');
});   

Schema::create('buy_codec', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('buy_id')->unsigned();
    $table->foreign('buy_id')->references('id')->on('buys')->onDelete('cascade');

    $table->integer('codec_id')->unsigned();
    $table->foreign('codec_id')->references('id')->on('codecs')->onDelete('cascade');

    $table->timestamps();
}); 

This is my controller:

   class UserBuyController extends Controller
{
    public function create($userId)
    {
        $codecs = Codec::lists('name', 'id');
        $usr = User::findOrFail($userId);
        return view('buy.create', compact('usr', 'codecs'));
    }

    public function store($userId, Request $request)
    {
        $codecs = $request->input('codecs');
        $usr = User::findOrFail($userId)->buy()->create($request->except('codecs'));
        $usr->codec()->sync($codecs);
        return redirect('user/'.$userId.'/buy');
    }

    public function edit($userId, $id)
    {
        $codecs = Codec::lists('name', 'id');
        $buy = User::findOrFail($userId)->buy()->findOrFail($id);
        return view('buy.edit', compact('buy', 'codecs'));
    }
}

Create form

{!! Form::open(['method'=>'POST', 'action'=>['UserBuyController@store', $usr->id]]) !!}

    <div class="form-group">
        {!! Form::label('name', 'Name:') !!}
        <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-font"></i></span>
            {!! Form::text('name', null, ['class'=>'form-control']) !!}
        </div>
    </div>

    <div class="form-group">
        {!! Form::label('codecs', 'Outbound Codecs:') !!}
        <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-language"></i></span>
            {!! Form::select('codecs[]', $codecs, null, ['class'=>'form-control', 'multiple'=>true]) !!}
        </div>
    </div>

    {!! Form::submit('Submit', ['class'=>'btn btn-info']) !!}

{!! Form::close() !!}

And this is the edit form

  {!! Form::model($buy,['url'=>url('user/'.$buy->user->id.'/buy/'.$buy->id),'method'=>'patch']) !!}

    <div class="form-group">
        {!! Form::label('name', 'Name:') !!}
        <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-font"></i></span>
            {!! Form::text('name', null, ['class'=>'form-control']) !!}
        </div>
    </div>

    <div class="form-group">
        {!! Form::label('codecs', 'Outbound Codecs:') !!}
        <div class="input-group">
            <span class="input-group-addon"><i class="fa fa-language"></i></span>
            {!! Form::select('codecs[]', $codecs, null, ['class'=>'form-control', 'multiple'=>true]) !!}
        </div>
    </div>

    {!! Form::submit('Update', ['class'=>'btn btn-info']) !!}

{!! Form::close() !!}

Model binding doesn't work

Something is wrong but I don't know what.



via Chebli Mohamed

lundi 24 octobre 2016

Laravel 5.1 Moving from one Ubuntu 14.04 to another

I am trying to moving my Laravel 5.1 app from one Ubuntu 14.04 server to another. I have updated the installed composer, database info, the app key, cleared cache and the sites-enabled points to the public directory. However instead of app up and running all I see is the text of the index.php file. Any thoughts?



via Chebli Mohamed

How to change environment values dynamically

How to change environment values dynamically in Laravel 5.1

Thanks!



via Chebli Mohamed

Issue in calling a Stored Procedure in Laravel

I'am calling a MySQL stored procedure using laravel as below,

$items = DB::select(
        'call sp_name(?, ?, ?)',
        array(
            $param1, $param2, $param3
        )
    );

this worked perfectly until today.

ISSUE

When we call route related to this Store procedure call, page keeps loading nothings happens, But at the same time if we log in to MySQL and do a manual call to Store procedure using a query as CALL sp_name($param1, $param2, $param3); went successful.

Can someone please explain why Store procedure fails when the calling happens through Laravel?



via Chebli Mohamed

laravel 5.1 how to overwrite validation class by own services?

Below is the implementation for nice validation label in Laravel 5.2. http://ift.tt/2e3OeR8

How do I implement the above method in my Laravel 5.1? i don't think i would want to direct edit the vendor file. what is the correct way to write my own validation to implement the nice validation for the label.

i am not going to upgrade my Laravel 5.2 or 5.3 due to we want the LTS version.



via Chebli Mohamed

Laravel: return model with relations

I'm trying to query a model with a relation.

My method:

public function getLabel($layerId)
{

    $labelGroups = Forum_label_group::with('labels')
        ->join('forum_layer_to_labels', function ($join) use ($layerId) {
            $join->on('forum_layer_to_labels.layerId', '=', 'forum_label_groups.id');
        })->with('labels')->get()->toJson();

    return $labelGroups;
}

The output:

[{"id":4,"name":"Demogruppe","description":"bla","required":1,"created_at":"2016-10-22 12:29:27","updated_at":"2016-10-22 12:29:27","labelGroupId":2,"layerId":2,"labels":[]},{"id":5,"name":"Demogruppe 2","description":"bla 2","required":0,"created_at":"2016-10-22 12:29:27","updated_at":"2016-10-22 12:29:27","labelGroupId":2,"layerId":3,"labels":[]}]

As you can see, the label relation is empty.

Now I'm trying to query a single model instead off all:

public function getLabel($layerId)
{
    return Forum_label_group::with('labels')->first()->toJson();
}

the new output:

"{"id":2,"name":"Demogruppe","description":"bla","required":1,"created_at":"2016-10-22 12:29:27","updated_at":"2016-10-22 12:29:27","labels":[{"id":5,"title":"Demo rot","name":"demo-rot","typeId":3,"groupId":2,"created_at":"2016-10-22 12:29:47","updated_at":"2016-10-22 12:29:47"},{"id":6,"title":"Demoblau","name":"demoblau","typeId":1,"groupId":2,"created_at":"2016-10-22 12:30:03","updated_at":"2016-10-22 12:30:03"}]}"

And as you can see now, everything is fine. The whole relation exists. Is there a problem with the initial query? The relation seems to be ok.



via Chebli Mohamed

How to allow emty value for Laravel numeric validation

How to set not require numeric validation for Laravel5.2? I just used this Code but when i don't send value or select box haven't selected item I have error the val field most be numeric... I need if request hasn't bed input leave bed alone. leave bed validate ...

$this->validate($request, [
        'provinces_id' => 'required|numeric',
        'type' => 'required',
        'bed' => 'numeric',
]);



via Chebli Mohamed

dimanche 23 octobre 2016

laravel take posts not registerd by this user

How can i take posts not registered by this user ? I create posts by This Code :

Auth::users()->post()->create($request->all());

I can get user posts with

users()->post()->all();

but i need to take count of posts created by other users.



via Chebli Mohamed

How can i sum multiple time in laravel 5.2

For example, I have multiple time like:

  $a = "9:00:00";
  $b = "8:00:00";
  $c = "9:00:00";

and so on...

It must return in 27:00:00 and how to subtract it from 45:00:00 ...

Please help.



via Chebli Mohamed

samedi 22 octobre 2016

Avoiding Constructor Dependency Injection in trait

I have a trait and that trait is being used in controller. In this way, many functions of trait are being used in Controller. Controller is extending a Base Controller. Controller and BaseController already have their constructor.

Due to some reasons, I need constructor in trait also because I needed Constructor dependency Injection in trait. Now, when I place constructor in trait, constructor does not execute.

In order to overcome this problem, I saw SendsPasswordResetEmails trait at this location \vendor\laravel\framework\src\Illuminate\Foundation\Auth\SendsPasswordResetEmails.php. You will see there is function called broker in this trait which returns a contract. In this way, they did not need Constructor Dependency Injection because they are getting Contract from the broker function

I already have a ServiceProvider which looks like below.

class RoleServiceProvider extends \Illuminate\Support\ServiceProvider {

    public function register() {
        $this->app->bind(
            'App\Architecture\Contract\Role\IRole', 
            '\App\Architecture\Database\Role\RoleDb'
        );
    }

    public function provides() {
        return ['App\Architecture\Contract\Role\IRole'];
    }
}

App\Architecture\Contract\Role\IRole is a Contract. \App\Architecture\Database\Role\RoleDb is a Database class

Question: Can you kindly tell how would I connect this Service Provide through Facade like it was done in SendsPasswordResetEmails trait to avoid Constructor Dependency Injection in trait ?



via Chebli Mohamed

how broker() function in trait SendsPasswordResetEmails return \Illuminate\Contracts\Auth\PasswordBroker?

I am using Laravel 5.3, In Forgot Password Controller, there is Trait SendsPasswordResetEmails

if you go to it's definition, there is function called broker(), it returns contract of type \Illuminate\Contracts\Auth\PasswordBroker

if you go to \Illuminate\Contracts\Auth\PasswordBroker , there is no function declaration with the name of broker()

and not even in it's derived class \Illuminate\Auth\Passwords\PasswordBroker.php

I saw it was present in \Illuminate\Auth\Passwords\PasswordBrokerManager.php

Question: Can you kindly tell how broker() function in trait SendsPasswordResetEmails return \Illuminate\Contracts\Auth\PasswordBroker ?



via Chebli Mohamed

vendredi 21 octobre 2016

How to access a property value inside JsonResponse Object in PHP or Laravel?

I'm doing a POST using Ajax and my Server is getting the data just fine. However, I'm struggling to access the value the user sent. In simple words how can I access the value of "user" (tom) ?. Anyone could get me on the right track please. Thank you in advance. Here's my JsonResponse object:

[2016-10-22 05:10:49] local.INFO: From Ajax: Illuminate\Http\JsonResponse Object
(
[data:protected] => {"user":"Tom","_token":"uRZJBVHH3worhjX4Ul6WlnJC1JYh3EVMNWob7Azr"}
[callback:protected] => 
[encodingOptions:protected] => 0
[headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object
    (
        [computedCacheControl:protected] => Array
            (
                [no-cache] => 1
            )

        [cookies:protected] => Array
            (
            )

        [headerNames:protected] => Array
            (
                [cache-control] => Cache-Control
                [content-type] => Content-Type
            )

        [headers:protected] => Array
            (
                [cache-control] => Array
                    (
                        [0] => no-cache
                    )

                [content-type] => Array
                    (
                        [0] => application/json
                    )

            )

        [cacheControl:protected] => Array
            (
            )

    )

[content:protected] =>     {"user":"Tom","_token":"uRZJBVHH3worhjX4Ul6WlnJC1JYh3EVMNWob7Azr"}
[version:protected] => 1.0
[statusCode:protected] => 200
[statusText:protected] => OK
[charset:protected] => 
)



via Chebli Mohamed

Continue where you left off not ending session in laravel

Even after setting

'expire_on_close' => true

Session continues. whereas in banking system,chrome feature of "continue from where you left" doesn't affects and session are ended properly when browser is closed.How i can configure same in my laravel setup.

When "continue from where you left" feature is enabled, chrome doesn't closes completely, it keeps running in the background.

Any help or suggestion ?



via Chebli Mohamed

Laravel 5: Undefined variable return_array [duplicate]

This question already has an answer here:

I'm trying to get data with ajax call, and after sending the ajax call i want to store data in array, but I'm getting this error when I open the page.

Undefined variable: return_array

My function

public function findUser(Request $request) {
    $findUserInput = $request->get('name');
    $user = DB::table('users')
        ->where('name', $findUserInput)
        ->first();

    $data =  DB::select("SELECT * FROM users WHERE name='$user'");

    foreach ($data as $da) {
        $return_array[] = $da;
    } 

    return $return_array;      
}

Any ideas?



via Chebli Mohamed

jeudi 20 octobre 2016

Laravel 5.1 | Issue while handling CSRF / XSRF tokens

I have a very possible silly doubt as I am not used to this concept of XSRF & CSRF, I do know the use of CSRF protection to some extent and currently working on a project, I came across this piece of code in the Laravel 5.1 VerifyCSRFToken middleware which is built in, I have a a strong doubt in below line of code.

protected function tokensMatch($request) {

        $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');

        if (!$token && $header = $request->header('X-XSRF-TOKEN')) {

            $token = $this->encrypter->decrypt($header);
        }

        return Str::equals($request->session()->token(), $token); 
}

Why is CSRF token is being matched for just a session token while XSRF is being decrypted as a encrypted string , I caught this doubt since my XSRF token is generated using just Session::token() method , But while the next post request the X-XSRF-TOKEN carries that token and lands on this middleware where that is decrypted and throws a Invalid Payload Data error with an exception :(



via Chebli Mohamed

Request URL using Laravel Task Scheduling

Environment

  • Laravel Version : 5.1.45 (LTS)

  • PHP Version : 5.6.1


Description

I'm trying to hit a certain route every minute.


Attempt

I've tried

$schedule->exec('curl '.env('APP_URL').'fbwifi/acl_update')->everyMinute()
        ->sendOutputTo(public_path().'/tasks/log.txt');


Kernel.php

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\Inspire::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->exec('curl '.env('APP_URL').'fbwifi/acl_update')->everyMinute()
        ->sendOutputTo(public_path().'/tasks/log.txt');
    }
}


Is what I did is the best way to make a GET to a route ? or is there a better way I should look into ?


I'm opening to any suggestions at this moment.

Any hints / suggestions / helps on this be will be much appreciated !



via Chebli Mohamed

Laravel (5.3) Passport: Password Grant issues and Possible Answers

I, like many others, have been having serious issues with the password grant. So I'm just taking a moment to post up the links I've been to so other's who feel lost may have some hope of where to go. (You never know these days)

Links

Adding Feilds to Password Grant: http://ift.tt/2ewCbM1

Adding Custom Grants Package?? : http://ift.tt/2eqHJYf

Making personal Access Tokens: http://ift.tt/2ewDZon

Helpful Note for Personal Access Tokens: http://ift.tt/2dDgeNC

The P100Y Problem: http://ift.tt/2ewCxCf

Possible Bugs

http://ift.tt/2dDhjFf

I've come across some other useful links too but if anyone else knows of some please share so those who are lost may have a chance at finding an answer.



via Chebli Mohamed

Laravel 5.1 Background Task that Queries Database Fails to Work when hooked to an Azure Web Job

I am having a strange problem using WebJobs on Azure to run Laravel Background tasks.

I have this code in my Laravel ExpireContactsFromDatabase command's handle() method

public function handle()
    {

    * Update contacts that are old and past their expiry date but that have not been deleted
    * Set their deleted at to the current timestamp
    */
        $contact = Contact::where('expiry_date', '<=', date('Y-m-d H:i:s'))
            ->whereNull('deleted_at')
            ->update(array('deleted_at' => date('Y-m-d H:i:s')));
        Log::info("200" . " " . "Contacts clearing executed successfully, see response from db :::: " . serialize($contact));

    }

I have successfully registered this command in app\Console\Kernel.php, like so:

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Inspire::class,
        ExpireContactsFromDatabase::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('inspire')
            ->hourly();

        $schedule->command('expire:contacts')
            ->everyMinute()
            ->sendOutputTo('expired_contacts_results_dbresponse.txt');

    }
}

This is running very well on my local development machine. I configured a cron job on my laptop and it executes this command and expires the old contacts as expected.

The problem comes in when I migrate the application from localhost to Ms Azure. I configure a WebJob to run continuosly, give it the path to artisan and issue schedule run. I do this in using a .bat file, like so:

php D:\home\site\wwwroot\artisan schedule:run > D:\home\site\wwwroot\expired_contacts_results_confirmation.txt

PHP is on my web applications path so no worries.

The challenge is when the command executes/ when I run php artisan schedule::run and I check my log files, I see the response from the database (logged into expired_contacts_results_dbresponse.txt) as follows:

[2016-10-20 12:21:43] local.ERROR: exception 'PDOException' with message 'SQLSTATE[HY000] [2002] An attempt was made to access a socket in a way forbidden by its access permissions.
' in D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:55 

My guess is that the way laravel is connecting to the database has issues in this case. However, other components of my application use the same connection codes and they are working well so In am confused. Scouring the internet for an exact solution to this problem has not worked.

I am running my app on Azure on the D1 Shared Hosting Plan and using the convenient Azure MySQLInApp database for my database storage.

Here is my full stack trace.

Stack trace:
#0 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php(55): PDO->__construct('mysql:host=;dbn...', '', '', Array)
#1 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Connectors\MySqlConnector.php(22): Illuminate\Database\Connectors\Connector->createConnection('mysql:host=;dbn...', Array, Array)
#2 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Connectors\ConnectionFactory.php(60): Illuminate\Database\Connectors\MySqlConnector->connect(Array)
#3 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Connectors\ConnectionFactory.php(49): Illuminate\Database\Connectors\ConnectionFactory->createSingleConnection(Array)
#4 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\DatabaseManager.php(175): Illuminate\Database\Connectors\ConnectionFactory->make(Array, 'mysql')
#5 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\DatabaseManager.php(67): Illuminate\Database\DatabaseManager->makeConnection('mysql')
#6 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(3224): Illuminate\Database\DatabaseManager->connection(NULL)
#7 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(3190): Illuminate\Database\Eloquent\Model::resolveConnection(NULL)
#8 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(1870): Illuminate\Database\Eloquent\Model->getConnection()
#9 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(1813): Illuminate\Database\Eloquent\Model->newBaseQueryBuilder()
#10 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(1787): Illuminate\Database\Eloquent\Model->newQueryWithoutScopes()
#11 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(3442): Illuminate\Database\Eloquent\Model->newQuery()
#12 [internal function]: Illuminate\Database\Eloquent\Model->__call('where', Array)
#13 [internal function]: App\Contact->where('expiry_date', '<=', '2016-10-20 12:2...')
#14 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(3458): call_user_func_array(Array, Array)
#15 D:\home\site\wwwroot\app\Console\Commands\ExpireContactsFromDatabase.php(53): Illuminate\Database\Eloquent\Model::__callStatic('where', Array)
#16 D:\home\site\wwwroot\app\Console\Commands\ExpireContactsFromDatabase.php(53): App\Contact::where('expiry_date', '<=', '2016-10-20 12:2...')
#17 [internal function]: App\Console\Commands\ExpireContactsFromDatabase->handle()
#18 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Container\Container.php(507): call_user_func_array(Array, Array)
#19 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Console\Command.php(150): Illuminate\Container\Container->call(Array)
#20 D:\home\site\wwwroot\vendor\symfony\console\Command\Command.php(256): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#21 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Console\Command.php(136): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#22 D:\home\site\wwwroot\vendor\symfony\console\Application.php(846): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#23 D:\home\site\wwwroot\vendor\symfony\console\Application.php(190): Symfony\Component\Console\Application->doRunCommand(Object(App\Console\Commands\ExpireContactsFromDatabase), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#24 D:\home\site\wwwroot\vendor\symfony\console\Application.php(121): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#25 D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php(107): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#26 D:\home\site\wwwroot\artisan(36): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

Will greatly appreciate any help I can get.



via Chebli Mohamed

Undefined property: stdClass:: error in Laravel 5.1

I got an error when i trying to print a value of an array in my Laravel Application.Please take a look.

My Controller:

public function index()
{
    //
    $data = new Userflow();
    $result = $data->gobalsCount();
    $res = $data->yrLogins;
    $res1 = $data->mnLogins;
    $res2 = $data->dayLogins;
    $res3 = $data->hrLogins;
    $res4 = $data->minLogins;
    $res5 = $data->secLogins;
    $object = [$res,$res1,$res2,$res3,$res4,$res5];

   //dd($object);
    return view('userflow',compact('object'));
}

My blade template:

  @foreach($object as $value)
  <td></td>                 
  @endforeach

In this way i got this type of error.If i var_dump($object) then it returns:

array:6 [▼
  0 => array:1 [▼
    0 => {#1396 ▼
      +"avg": "2.0000"
    }
  ]
  1 => array:1 [▶]
  2 => array:1 [▶]
  3 => array:1 [▶]
  4 => array:1 [▶]
  5 => array:1 [▶]
]

Any help will be appreciated.Thanks in advance.



via Chebli Mohamed

mercredi 19 octobre 2016

Email signing in Laravel 5.1

I apologise in advance if this is an amateurish question. I am trying to setup my app in laravel 5.1 so when a user signs up they can send emails from their domain via mycompanydomain.com.

They currently have to add their own SMTP details to send outbound emails from their accounts but its putting strain on our support.

Is there an easy enough way to achieve this OR anything I can use from Git?



via Chebli Mohamed

Cant internal rewrite pretty url with laravel and htaccess

I'm having a problem doing internal rewrites with apache/htaccess and Laravel 5.1. The scenario is quite simple, I have some routes working on my app that needs to be rewritten to a more human/SEO/Customer friendly URL, my initial approach was simply rewrite them in htaccess as I did so many times.

However the, problem rises when I try to do it and it does not work at all, for example, if I have the url http://ift.tt/2ekeStU and I want to rewritte to http://ift.tt/2dqbTtX

Normally i would do:

RewriteRule ^dummy-dummy-dummy-id.html /myroute/$4

However when I follow this pattern with this laravel project I got a 404 error, i have been doing tests for some days and it does not matter what to do, it will always give you a 404 unless using the flag [R] wich redirects de request externally instead of the internal behaivor i need.

I have been using a dd() in the AppServiceProvider to see the details of the request the framework is getting and the URI it gets is allwas the friendly one (so the internal redirect does not reach the index.php) I have been looking at the mod_rewrite debug logs and looks like it is working fine matching the friendly url and doing and internal rewrite, but it never reaches the framework :(

this is the full htaccess:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    php_value upload_max_filesize 30M
    php_value post_max_size 6M

    RewriteEngine On

    RewriteCond %{HTTP_HOST} !^www\.
    RewriteCond %{HTTP_HOST} !^local\.
    RewriteCond %{HTTP_HOST} !^beta\.
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    RewriteRule ^dummy-dummy-dummy-id.html /myroute/$4

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

NOTE: I know that I can implement the friendly routes straight in the routes file of laravel, but I don't understand why this is not working so I would like to find out.



via Chebli Mohamed

Laravel 5.3 “group by count” query issues

Please I am trying to run a query that looks like this in raw sql

SELECT `qnty`, COUNT(*) FROM cartlist GROUP BY `pro_id`,`cart_id`,`price`

in laravel.

I have tried this

$count = DB::table('cartlist')
                 ->select(DB::raw('count(*) as qnty'))
                 ->where('pro_id', '$tt->pro_id')
                 ->where('cart_id', '$cart_id')
                 ->groupBy('pro_id','price')
                 ->get();

But it gives the following error

Object of class Illuminate\Support\Collection could not be converted to int



via Chebli Mohamed

mardi 18 octobre 2016

How to write raw query in Laravel 5.1?

I am beginner in Laravel.I can write query in raw PHP.Now i want to write it in Laravel framework.I have read documentation and tried so far:

In Raw PHP:

SELECT count(*)/(TIMESTAMPDIFF(YEAR,'2016-01-01 00:00:00',now())+1) as avg from buyer  where created_at >= '2016-01-01 00:00:00';

Tried with Laravel:

public function index()
{
    //
    $yrUserReg = DB::table('buyer')
                    -> SELECT (DB::raw (count('*')/("TIMESTAMPDIFF(YEAR,'2016-01-01 00:00:00',now())+1"))) 
                    -> AS ('avg') 
                    -> WHERE ("created_at >= '2016-01-01 00:00:00'");
   return view('userflow',compact($yrUserReg));                 
}

But it throws me an error: Division by Zero.I can not find any solution of this. Thanks in advance.



via Chebli Mohamed

Token value change on page reload laravel 5.2

why Token value changes on page reload laravel 5.2 ?,hence session does not persist it returns only token

return Session::all();



via Chebli Mohamed

Laravel 5.1 Sessions not working

I have fresh Laravel 5.1 distribution. The first thing I started from is to extend the Guard class in order to implement my own auth driver. I'm really new with Laravel. So, here is what I did so far.

config/auth.php

'driver' => 'crm',

Providers/AuthServiceProvider.php

   public function boot(GateContract $gate)
    {
        Auth::extend(
            'crm',
            function ($app) {
                $model = $app['config']['auth.model'];
                $provider = new EloquentUserProvider($app['hash'], $model);

                return new CrmGuard($provider, $app->make('session.store'));
            }
        );
    }

Currently, I already have a user id, stored in session array and I can access it via

session_start();
$_SESSION['user_id'];

But I want to use a Laravel build in session management. I'm trying to rewrite user method of Guard class in my CrmGuard class and I need to get those values from session, I was trying like so

$id = $this->session->get('user_id');

and so

session('user_id')

But it always return NULL, what I did wrong? Thank you.



via Chebli Mohamed

lundi 17 octobre 2016

Validation of type Request Laravel

Good friends greetings to all ...

I have a question and want to know if I can solve the Request validation method.

I have a table called condando and another called town.

In laravel I'm creating a view where once the chosen condando Select a drop-down should write the town, the idea is to associate localities with condandos.

Eg serious Dallas County town Texas in the United States.

So I'm working with the creation of the town, and as you know in laravel there is the option to create validations using the command:

 php artisan make:request nombredelrequest

I created my validations and so far I like this:

public function rules()
{
    return [
        'condado_id'=>'required',
        'nomb_localidad'=>'required'
        //
    ];
}
public function messages()
{
    return [
        'condado_id.required'=>'Necesitamos que elija un condado',
        'nomb_localidad.required'=>'Necesitamos el nombre de la localidad'
    ];

}

So far I'm telling you need to have the town and county, but I would somehow using this type of validation that if I try to register again the same town in the same county tell me it's not possible for already exists. Darce be the case that a town has a name exists in one county and another county a town with the same name that may be possible, I need to validate that if condando already exists in the area do not let me register.

I hope you can help me thank you very much ...



via Chebli Mohamed

How can I retrieve data from a table in laravel with multiple array conditions

Im applying a search filter in a e-commerce website. Here the Customer can choose various fields like color, shape, price, symmetry,polish,clarity and various other things. While the Customer selects any option it should add to the last option he have selected.So he/she may have combination of condition which have to be fetched and shown. For one array condition i can use whereIn in laravel but for multiple array conditions what should I use.Im not sure which array will be empty.

Here is my code for filter :-

public function Filter(Request $request)
{
    $conditions = array();
    if($request->isMethod('post')) {
        $data = array_filter($request->all());

        $shapes = array();
        $amount = array();
        $carat  = array();
        $cut  = array();
        $color = array();
        $clarity = array();
        $cerifying_agency = array();
        $flourscence = array();
        $polish = array();
        $symmetry = array();
       // $conditions=array();
        if(isset($data['shape'])){
            $shapes = $data['shape'];
        }
        if(isset($data['amount'])){
            $amount = $data['amount'];
        }
        if(isset($data['carat'])){
            $carat = $data['carat'];
        }
        if(isset($data['cut'])){
            $cut = $data['cut'];
        }
        if(isset($data['color'])){
            $color = $data['color'];
        }
        if(isset($data['clarity'])){
            $clarity = $data['clarity'];
        }
        if(isset($data['ca'])){
            $cerifying_agency = $data['ca'];
        }
        if(isset($data['fl'])){
            $flourscence = $data['fl'];
        }
        if(isset($data['polish'])){
            $polish = $data['polish'];
        }
        if(isset($data['symmetry'])){
            $symmetry = $data['symmetry'];
        }

    }
}

I have attached the snapshot of the UI and the data format for ajax which is being called in the array of the filter function :-Sorry I couldnt embed the picture as Stackoverflow is not allowing me to do so



via Chebli Mohamed

Session not persist after login in live environment laravel 5.2

Laravel 5.2 Session does not persist after login ,I have had problem with CSRF token so i removed it from kernel.php , it works fine in local environment can it be reason for session not working in live environment ?



via Chebli Mohamed

dimanche 16 octobre 2016

Date validation in Laravel

It appear there is no validation rule in Laravel that start_date and end_date can not be the same.

How do I overcome this?



via Chebli Mohamed

samedi 15 octobre 2016

Trait not calling Contructor

Controller code.

class RoleController extends \App\Http\Controllers\BaseController
{

    use RoleTrait;

    public function __construct() {
        parent::__construct();
    }
}

Trait

trait RoleTrait {

    private $Role;

    public function __construct(IRole $_role) {
        $this->Role = $_role;
    }

}

Issue

Trait is not calling constructor. Is there any way to call constructor in trait? I want to keep constructor in trait and also in Controller



via Chebli Mohamed

Laravel Auth registration Redirect to Home Page

I have login registration form which is built in auth.Every think is working properly. In Registration form Suppose if i enter plus(+) symbol in email like vision+name@gmail.com then it will directly redirecting to home page without confirmation of email.Can any one tell how to fix that issue



via Chebli Mohamed

vendredi 14 octobre 2016

looping through array to get data using eloquent inside eloquent query

I'm programming a tourism agency website. I've hotels in database which have a column called stars which is an integer its value is between 1 to 5.

I have a form which the user can search hotels based on their stars. The field is checkbox so he can search five stars and four stars hotels together for example.

I read the stars array and redirect the visitor to the search page using this code:

$stars_param = "";
    $i = 1;
    foreach($stars as $star){
        if($i == 1){
            $stars_param .= $star; 
        }else{
            $stars_param .= "&".$star;
        }
        $i++;
    }
    $parameters = "filter=true&&stars=".$stars_param."&&price=".$price."&&area=".$area;
    return \Redirect::to('/hotels-search/?'.$parameters); 

So the url will be like this:

hotels-search?filter=true&&stars=5&1&&price=300&&area=taksim

And in the hotels-search page I read the $_GET , and explode the stars variable and coded this query to fetch data:

$stars = $_GET['stars'];
$stars_array = explode('&', $stars);
$price = $_GET['price'];
$area = $_GET['area'];
$this['hotels'] = \Lilessam\Hotels\Models\Hotel::orderBy('id', 'desc')->where('stars',  function($query) use($stars_array){
                $i = 1;
                foreach($stars_array as $star){
                    if($i == 1){
                        $query->where('stars', $star);
                    }else{
                        $query->orWhere('stars', $star);
                    }
                    $i++;
                }

                })->where('price', '<=', $price)->whereHas('area', function($query) use($area){
                                $query->where('name', 'LIKE', $area);
                                })->paginate(5);

But with this I got this error from database !

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where `stars` = ?) and `price` >= ? and (select count(*) from `lilessam_hotels_a' at line 1 (SQL: select count(*) as aggregate from `lilessam_hotels_hotels` where `stars` = (select * where `stars` = 5) and `price` >= 300 and (select count(*) from `lilessam_hotels_areas` where `lilessam_hotels_hotels`.`area_id` = `lilessam_hotels_areas`.`id` and `name` LIKE taksim) >= 1)

How can I make a query so I can get hotels with 1 or 3 or 5 stars at the same time?!



via Chebli Mohamed

jeudi 13 octobre 2016

Any alternative of mysql_real_escape_string in laravel 5.2

How to use mysql_real_escape_string in laravel 5.2,i get to now laravel use PDO can anyone give exaple of that?



via Chebli Mohamed

Getting error after composer update

I am getting the following errors after a composer update on a Laravel project:

Warning:require(/home/vagrant/Code/acme/vendor/composer/../../app/helpers.php): 
failed to open stream: No such file or 
directory in /home/vagrant/Code/acme/vendor/composer/autoload_real.php 
on line 66

Call Stack

1   0.0005  361704  {main}( )   .../index.php:0

2   0.0021  361952  require( '/home/vagrant/Code/acme/bootstrap/autoload.php' ) .../index.php:22

3   0.0177  362944  require( '/home/vagrant/Code/acme/vendor/autoload.php' )    .../autoload.php:17

4   0.0214  364424  ComposerAutoloaderInite893eea6f4734f123846aeff2dfd0c15::getLoader( )    .../autoload.php:7

5   0.1658  506328  composerRequiree893eea6f4734f123846aeff2dfd0c15( )  .../autoload_real.php:56

and the following error:

Fatal error: require(): Failed opening required '/home/vagrant/Code/acme/vendor/composer/../../app/helpers.php' (include_path='.:/usr/share/php') in /home/vagrant/Code/acme/vendor/composer/autoload_real.php on line 66
Call Stack

1   0.0005  361704  {main}( )   .../index.php:0

2   0.0021  361952  require( '/home/vagrant/Code/acme/bootstrap/autoload.php' ) .../index.php:22

3   0.0177  362944  require( '/home/vagrant/Code/acme/vendor/autoload.php' )    .../autoload.php:17

4   0.0214  364424  ComposerAutoloaderInite893eea6f4734f123846aeff2dfd0c15::getLoader( )    .../autoload.php:7

5   0.1658  506328  composerRequiree893eea6f4734f123846aeff2dfd0c15( )  .../autoload_real.php:56

Line 66 of /home/vagrant/Code/acme/vendor/composer/autoload_real.php is the the line require $file; of the following method:

function composerRequire1601035f2d74a33e13617fd13fa9786b($fileIdentifier, $file)
{
    if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
        require $file;

        $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
    }
}

I have tried to completely re-install the composer dependencies by the following:

  • run rm -r vendor
  • run rm composer.lock
  • run composer clear-cache
  • run composer install

But this has had no effect and the errors persists with a fresh install.



via Chebli Mohamed

laravel 5.1 download docx file not working

Im trying to force the download a docx file from a folder (named 'cvs') in the public folder and is not working. I don't get an error it just shows a lot of weird symbols in the console instead of pushing the download. in my controler what i do is this:

return response()->download(public_path('cvs/56_dummyFile.pdf', 'CV-'.$details['applicant'].$doxType));

Note: $doxType is just the extension.

in this example im forcing (or trying) the download, but no download happens. The response from the server is ok and all i can see in the response is (this is just a fragment):

`3��b�6�0Ln3�ę�ӯH.x��֠��P�"U�j�+�g��L���7PCc�6����s�2O�f��kc��j|]�Q�?�t�Z�����������r%?o��@��2��ʪJ�L�\_�3$h(�u���DO�'O��0ׯ=��J������U��}�v�W��>�,�������u�@C�]l���>`

any ideas? Thanks in advance!



via Chebli Mohamed

Best way to store images in database and display directly from database in model?

What is the the best way to store and display images in the model directly from the database. I do not want to save to local storage or load from database in the controller and then pass to model. If possible.Thanks in advance.



via Chebli Mohamed

laravel Auth::login login not working

here is my code i am trying to login but its not working, data comes till before but something wrong in -> Auth::login($user1); though if i put Auth::login($user1); in if() condition it goes inside but not redirect in if condition,

        if(count($staff) > 0)
       {
       $staff['0']['type']='staff';
        $staff['0']['name']=$staff['0']['emp_name'];

        unset($staff['0']['emp_name']);
        Session::put('user',$staff['0']);

        $id= $staff[0]['id'];

        $user1 = Staff::find($id);
        //print_r($user);exit;
        //return Auth::login($user);
        Auth::login($user1);

        return redirect()->intended('/student');

    }



via Chebli Mohamed

mardi 11 octobre 2016

Laravel permission issue in server

I have given 'storage/framework/session' folder to 755 recursively but session created inside it has 644 in server,can anyone tell me why it is?



via Chebli Mohamed

MethodNotAllowedHttpException in RouteCollection.php in laravel 5.1

This is the code and I am working on form and when I submit the form, it shows this error:

MethodNotAllowedHttpException in RouteCollection.php line 218

Here is my code:

UserController.php

    <?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function postSignUp(Request $request){

        $email=$request['email'];
        $first_name=$request['first_name'];
        $password=bcrypt($request['password']);

        $user= new User();
        $user->email=$email;
        $user->first_name=$first_name;
        $user->password=$password;

        $user->save();
        return redirect()->back();

    }


}

routes.php

<?php


Route::get('/', function () {
    return view('welcome');
});

Route::post('/signup',[
        'uses' => 'UserController@postSignUp',
        'as' => 'signup'
    ]);

welcome.blade.php

@extends('layouts.master')

@section('title')
    Welcome!
@endsection

@section('content')
    <div class="row">
        <div class="col-md-6">
            <h3>Sign Up</h3>
            <form action="" mathod="post">
                <div class="form-group">
                   <label for="email">Email</label> 
                  <input type="email" class="form-control" name="email">
                </div>

                <div class="form-group">
                   <label for="first_name">Your First Name</label>  
                  <input type="text" class="form-control" name="first_name">
                </div>

                <div class="form-group">
                   <label for="password">Password</label>   
                  <input type="password" class="form-control" name="password">
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
                <input type="hidden" name="_token" value="">
            </form>

        </div>



    </div>
@endsection

Please note that I am working on laravel 5.1 & I am a beginner. Can you please help me to solve the problem?



via Chebli Mohamed

lundi 10 octobre 2016

Is it worth using entrust with Dingo API? Is there a better way?

I'm using Laravel 5 for my next project. I need to apply some role logic for the working. So here's what I've came up with:

$api = app('Dingo\Api\Routing\Router');

//admin routes!
$api->version('v1', ['middleware' => ['ability:admin,create-users']],
function ($api) {
$api->get('dingocheck', 'App\Http\Controllers\AdminController@index');
});

//store routes
$api->version('v1', ['middleware' => ['ability:store,create-products']],        
function ($api) {
$api->get('dingocheck', 'App\Http\Controllers\StoreController@index');
});

//userroutes
$api->version('v1', ['middleware' => ['ability:admin,puchase-products']],       
function ($api) {
$api->get('dingocheck', 'App\Http\Controllers\UserController@index'); });

I'm yet to resolve how to manage the modelling within the application. Thanks for help (:



via Chebli Mohamed

Laravel View [auth.login] not found after downloaded form bitbucket

My laravel project still online without any error, but when i downloaded my project form bitbucket to want to change something. it give me two error View [auth.login] not found.

and an another error bellow the first error failed to open stream: No such file or directory

i tried everything what i have on internet i tried composer-install composer clear-cache php artian clear-compiled but noting works for me.



via Chebli Mohamed

Accessing relationship of a relationship

I am adding in an announcements feature to my application.

I have an announcements table which stores the announcement and an announcement_active table which stores the undismissed announcements for each user.

When an announcement is created, a record is generated in the announcements table to store this and a record entered in to the announcement_active table for every user for that announcement.

My user model holds a relationship for the active announcements:

public function activeAnnouncements()
    {
        return $this->hasMany('App\ActiveAnnouncements');
    }

I am then accessing this in my view to check for any undismissed announcements like this:

@if (Auth::user()->activeAnnouncements()->count() > 0)
    //code
@endif

The above works fine, it is when I am trying to do a for each loop on the announcements that I am having trouble:

@if (Auth::user()->activeAnnouncements()->count() > 0)
    @foreach(Auth::user()->activeAnnouncements()->announcement as $announcement)
      //code to display announcement
   @endforeach
@endif

It is when I am chaining ->announcement that I run in to trouble. I have defined the relationship like so:

public function announcement()
    {
        return $this->belongsTo('\App\Announcements');
    }

However I get the error:

Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$announcement

When using Tinker and running \App\User::find(1)->activeAnnouncements()->first()->announcement the correct announcement shows.

Where am I going wrong when trying to load these in to my foreach loop?



via Chebli Mohamed

Laravel 5.1 File not deleting from folder

I want to delete a pdf file form my database as well as my public/uploads folder. It is deleting from the database but not from my public folder.

This is my controller:

 public function deleteArticle($id) {
    $article = Article::findOrFail($id);

     File::delete($article->document);
        $article->delete();
    return redirect()->back();
   }



via Chebli Mohamed

dimanche 9 octobre 2016

Laravel return a value if it is not unique

I am checking if the value is unique or not in the database using validation and here is the code:

 public function store(Request $request)
        {
            $select = 'select';

            //logged in user id
            $userid         = Auth::user() -> id;
            $usercountry    = Auth::user() -> country;

            $this -> validate($request, array(
                'number'        => 'required | unique:leads',
                'website'       => 'required | unique:leads',
                'lead_source'   => 'required | not_in:' . $select,
                'industry'      => 'required | not_in:' . $select,
                'action'        => 'required | not_in:' . $select
            ));
}

This works perfect but it show me a message telling me if the website input is duplicated or not.

What I am trying to do is to return a value from the table leads which contain the website column.

I found this code:

if ($validator->fails()) {
            $failedRules = $validator->failed();

        }

How I could modify it to return a value from the same duplicated row in the leads table?



via Chebli Mohamed

samedi 8 octobre 2016

Laravel - FatalErrorException in usahaController.php line 33: Call to a member function paginate() on a non-object

I am making a search page in Laravel and cant understand how to use the paginate method for this usage.

I have used it else where, but not like this. usahaController

    public function feindex()
{
    $hasil= DB::select('sELECT anggota.USERNAME, kategori_usaha.NAMA_KATEGORI_USAHA, usaha.NAMA_USAHA, 
        usaha.TYPE_UMKM, usaha.GAMBAR_UMUM, usaha.ALAMAT_USAHA, usaha.NOMOR_TLPN_USAHA FROM usaha 
        JOIN anggota on usaha.ID_ANGGOTA=anggota.ID_ANGGOTA 
        JOIN kategori_usaha on usaha.ID_KATEGORI_USAHA=kategori_usaha.ID_KATEGORI_USAHA')->paginate(2);
    $keranjang['usaha']=$hasil;  
    return view('feindex', $keranjang);

}

view

            @foreach ($usaha as $item)
        <div class="col-sm-6 col-md-3">
            <div class="thumbnail text-center">

                <a href="single_product.html"><img src="" class="img-responsive"></a>
                <br/>
                <h5 class="text-primary"></h5>
                <ul>
                    <li><i class="livicon" data-name="check" data-size="18" 
                    data-loop="true" data-c="#787878" data-hc="787878"></i> Nama Pengusaha :<br>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</li>
                    <li><i class="livicon" data-name="check" data-size="18" 
                    data-loop="true" data-c="#787878" data-hc="787878"></i> </li>
                    <li><i class="livicon" data-name="check" data-size="18" 
                    data-loop="true" data-c="#787878" data-hc="787878"></i>  </li>
                    <li><i class="livicon" data-name="check" data-size="18" 
                    data-loop="true" data-c="#787878" data-hc="787878"></i> </li>
                    <li><i class="livicon" data-name="check" data-size="18" 
                    data-loop="true" data-c="#787878" data-hc="787878"></i>  </li>
                </ul>
                <a href="single_product.html" class="btn btn-primary btn-block text-white">View</a>
            </div>
        </div>
        @endforeach
        {!! $usaha->render() !!}

how fix this



via Chebli Mohamed

laravel 5.2 multi user authentication from multiple tables using package

please suggest any package for multiple user authentication from multiple tables in Laravel



via Chebli Mohamed

laravel 5.2 session flash working on localhost but not working on server?

Session flash working fine on local but not working on server in laravel5.2 ?

In controller

Session::flash('key', value"); return Redirect::to('/');

 In view

@if (Session::has('key') && Session::get('key')!='')

alert('.......'); @endif

})



via Chebli Mohamed

vendredi 7 octobre 2016

laravel 5.2 Session not persist after login

Laravel 5.2 Session not persist after login, I have not used any middleware or default laravel auth for login. I used native php login code



via Chebli Mohamed

jeudi 6 octobre 2016

Multi user authentication laravel 5.2

can anyone tell me where to put below code in auth.php This is link i used for authentication

'multi' => [ 'user' => [ 'driver' => 'eloquent', 'model' => App\User::class, 'table' => 'users' ], 'admin' => [ 'driver' => 'eloquent', 'model' => App\Admin::class, 'table' => 'admins' ] ],



via Chebli Mohamed

Fatal error: Class 'App\Http\Controllers\Redirect' not found

when i run below command in my terminal it shows below code instead of routes

php artisan route:list



 <html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="1;url=http://localhost/login" />

        <title>Redirecting to http://localhost/login</title>
    </head>
    <body>
        Redirecting to <a href="http://localhost/login">http://localhost/login</a>.
    </body>
</html>

[Symfony\Component\Debug\Exception\FatalThrowableError] Fatal error: Class 'App\Http\Controllers\Redirect' not found



via Chebli Mohamed

mercredi 5 octobre 2016

Migrate data from table to different tables with Laravel

I'm working with an existent project on Laravel and I need to change current database schema and keep current data.

For example, I have this table in the initial migration:

Person

----------------------------------------------
| **Id**        |**Name**  | **PhoneNumber** |
----------------------------------------------
|             1 | John Doe | 111-55-5855     |
----------------------------------------------
|             2 | Jane Doe | 111-55-5521     |
----------------------------------------------

But now, I need to split this into two tables:

Person

----------------------------
| **Id**        |**Name**  |
----------------------------
|             1 | John Doe |
----------------------------
|             2 | Jane Doe |
----------------------------

Person Phone

---------------------------------------------------
| **PhoneId**   | **PersonId**  | **PhoneNumber** |
---------------------------------------------------
|             1 |             1 | 111-55-5855     |
---------------------------------------------------
|             2 |             2 | 111-55-5521     |
---------------------------------------------------

So, in the new migration I delete PhoneNumber from Person and add the new table PersonPhone.

Is there any way to map PhoneNumber to the new table and keep PhoneId and PersonId in Person table? Or the only way is create a MySQL script?



via Chebli Mohamed

Via Remember me always return false

Before I posted this, I did some searching but still I don't know it always return false. My code is below

html

<input type="checkbox" name="remember"/> 

controller

$remember = ($request->has('remember')) ? true : false;

if (Auth::attempt($credentials, $remember))

Then after successful logged-in. I checked the dd(Auth::viaRemember()); and it return false. Even changed my config/session.php setting 'expire_on_close' => true from false.

Basically what I want is when the user tick the remember me checkbox I will set the session lifetime to 3 days else to 1 day only.



via Chebli Mohamed

Multi authentication laravel 5.2

I find a lot but didn't get result ,which one is best way to multi Authentication laravel 5.2



via Chebli Mohamed

Get rows from database in laravel

Image one is "video_submission" table

Image one is "video_submission_transaction" table

I want to make group by job_no, same job_no should come under one group, how will be the laravel Query, from those two tables I should get 3 rows, both tables should have a join also,



via Chebli Mohamed

How do I bind a Model Object while using resource controller in Laravel 5.1

What I'm looking for is something like this

public function store(Help $help)
{
    $help->save();

    return response
}

I have added the model class is Routes.php file like this

Route::model('help', 'App\Help');
Route::resource('api/help', 'HelpController');

And this is my Help.php file

class Help extends Model
{
    use SoftDeletes;

    protected $primaryKey = 'id';

    protected $table = 'help';

    protected $dates = ['deleted_at'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = array('name','description','deleted_at','created_at', 'updated_at');

}

Binding is happening to an extent, i.e, there is a new row in the table but the attributes "name" and "description" are empty.



via Chebli Mohamed

mardi 4 octobre 2016

Is there any way to pass variable in rememberForever callback?

I have following code,

\Cache::rememberForever('Roles', function() {
    return RoleModel
        ::where('ParentRoleID' >= $CurrenctUserRoleID)
        ->get();
});

Issue is: I am getting Error

Undefined variable: CurrenctUserRoleID

Question: Is there any way to pass variable in callback?



via Chebli Mohamed

$this->clearLoginAttempts($request); is not working preperly?

I have Route like this.

Route::post('login',           
    array (
        'uses'          => 'Auth\LoginController@login',
        'as'            => 'postlogin',
        'middleware'    => ['throttle:3,1']
    )
);

Below mentioned method can be found in this file:

vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php

protected function sendLoginResponse(Request $request)
{
    $request->session()->regenerate();

    $this->clearLoginAttempts($request);

    return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
}

What am I doing?

I am authenticated Successfully and then pressed Logout button. I did the same thing 3 times. Each time I am authenticated successfully and then pressing logout button. On 4th attempt, I am locked for 1 minute.

What's the problem?

On successful login, this code $this->clearLoginAttempts($request); executes and clears the previous login attempts. Still I am locked. Why? Is it an issue in Laravel 5.3?



via Chebli Mohamed

Check if a value is present in a comma separated varchar string

I have a record "id_zone" in database that store cites id like this $abilitato->id_zone = '1, 2, 3, 9, 50' From laravel i need to check if a value passed from url is present in this field. The following work only if i have a single value

$abilitato = \App\Models\Servizi::where('id', $servizio)->('id_zone', $verifica->id_citta)->first();
                if(!empty($abilitato) && empty($verifica->multicap)) {
                $json = ['CAP' => '1' , 'DEB' => $cap ];
                    }else{
                $json = ['CAP' => '0' , 'DEB' => $cap];

            }

i need to check if



via Chebli Mohamed

lundi 3 octobre 2016

pdo drivers shows no value in linux

this is screenshot i have install php5.6 with the following command: - sudo apt-get install -y php5.6 and also install the php cli with this command : sudo apt-get install php5-cli.

then,

I have added following line to php.ini file for extenstion: extension=pdo.so and extension=pdo_mysql.so

and given the extension path : extension = /usr/lib/php/20131226/pdo_mysql.so

and use command : sudo apt-get install php-mysql

but still shows the pdo drivers no value when running phpinfo()

so, how to solve?



via Chebli Mohamed

Laravel 5.1 sync method with multiple attibutes as primary

I am using sync(on many to many) method in laravel 5.1 to add relational info to a user in DB.

My Table is

User-:

  • id(pk)
  • name
  • email

tags-:

  • id(pk)
  • name
  • slug

user_tags_mapping-:

  • user_id
  • tags_id
  • function
  • count

the relationship i have defined in between is a many to many

return $this->belongsToMany(
        tags::class, 'user_tags_mapping',
        'user_id', 'tags_id')->withTimestamps()
        ->withPivot('function', 'count');

Now i am using sync to insert value into this table like

$user->tags()->sync([tags_id => [function, count]]);

Now my problem is that when i use the same tags_id with different function the sync detaches the older value as the tags_is already exist.

Is There a way where i can use tags_id and function both as the parameters to sync to the table where function is a string value.

I have already defined the all the three parameter as primary inside the migration script, but it still didn't work.



via Chebli Mohamed

How do I implement Maker-Checker Concept in Laravel 5.2?

I have to implement maker-checker concept in laravel 5.2.
If User(Maker) does some changes(insert,update,delete), they will only be reflected after the Checker approves it. How can I implement it??
Thank You in Advance,



via Chebli Mohamed

dimanche 2 octobre 2016

add control to resource routes

My resource route looks like :

$router->resource('subnets', 'subnetController');

I saw on the documentation that a resource route can have an array of parameters... is there a parameter that permits you to choose who can access to those routes ? If I was using basic routing that would be something like :

Route::get('/subnets', function () {
   if (Auth::user()['attributes']['role'] == 'admin') return view('subnets.index');
   else return view ('errors.403');
});



via Chebli Mohamed

Issue while sending smtp email from Godaddy in Laravel 5.3.15

In order to send email from GoDaddy i am using below settings.

MAIL_DRIVER=smtp
MAIL_HOST=localhost
MAIL_PORT=465
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=ssl

I am getting error message

Connection could not be established with host localhost [Connection refused #111]

This setting was working fine in Laravel 5.2 but not working in Laravel 5.3

Did you face this kind of issue before?



via Chebli Mohamed

samedi 1 octobre 2016

Seed a recursive table using factories in Laravel

I have a recursive table in my Laravel project to handle a dynamic menu. For testing purposes I need to seed that table with random elements.

The name is not the problem (a random name would be okay). The main thing is how to generate the parent_id numbers. I'll show an example:

+---------------------------+
| id  | name    | parent_id |
+---------------------------+
| 1   | animals | 0         |
|---------------------------|
| 2   | food    | 0         |
|---------------------------|
| 3   | dog     | 1         |
|---------------------------|
| 4   | potato  | 2         |
|---------------------------|
| 5   | monkey  | 1         |
+---------------------------+

I don't want to generate a random number, because some entries of the table would not have any associated parent. And since the id is incremental, the parent_id must be associated with some id.

I've created the factory for the first level (the parent_id = 0). But I don't know how to continue now.

$factory->defineAs(App\Section::class, 'firstLevelMenu', function($faker) {
   return [
       'name' => $faker->unique->randomElement([
           'animals',
           'food'
       ]),
       'parent_id' => '0'
   ];
});



via Chebli Mohamed

How to show value in if statement in laravel

I am doing my project but got stuck in this. I want to print both value of degrees and experiences. How can i achieve this? My controller file is like below:

public function industryPost (Request $request) {
        $industry = $request->input('industry');

        if (empty($industry)) {
            return 'Industry can not be null';
        } else {

            $experiences = AreaOfExperience::where('industry_id', $industry)->where('is_active', 1)->where('is_deleted', 0)->get();
            $degrees = Degree::where('industry_id', $industry)->where('is_active', 1)->where('is_deleted', 0)->get();


            if (!empty($degrees) ) {
                $string2 = '';
                foreach ($degrees as $degree) {
                    $string2 .= '
                        <div class="col-md-4">
                            <div class="be-checkbox">
                                <label class="check-box">
                                    <input id="degree" type="checkbox" name="degrees[]" value="'.$degree->id.'" class="checkbox-input">
                                    <span class="check-box-sign"></span>
                                </label>
                                <span class="large-popup-text"> '.$degree->name.' </span>
                            </div>
                        </div>
                    ';
                }
                return response($string2);
            }
            if (count($degrees) == 0) {
                return 101;
            }

            if (!empty($experiences) ) {
                $string = '';
                foreach ($experiences as $experience) {
                    $string .= '
                        <div class="col-md-4">
                            <div class="be-checkbox">
                                <label class="check-box">
                                    <input id="experience" type="checkbox" name="area_of_experiences[]" value="'.$experience->id.'" class="checkbox-input">
                                    <span class="check-box-sign"></span>
                                </label>
                                <span class="large-popup-text"> '.$experience->name.' </span>
                            </div>
                        </div>
                    ';
                }
                return response($string);
            }
            if (count($experiences) == 0) {
                return 100;
            }


        }
    }

I want to print both the value of degree and experience. But in my query it prints the value of degree. how can i achieve this? Please help!



via Chebli Mohamed

Session does not persist in laravel

laravel 5.2 session does not persist , i have not used auth::check or any auth method for login check then how to put all my routes in middleware

Route::auth();



via Chebli Mohamed