lundi 12 septembre 2016

TokenMismatchException in VerifyCsrfToken in Laravel 5.1 + angular

I have Laravel 5.1 + angular form sending JSON request when user want to send mail from website feedback form.

I did my form according to documentation here http://ift.tt/2cmWmgK and anyway I get error message TokenMismatchException in VerifyCsrfToken.php line 53:

I found a lot of topics on stackoverflow, but no real solution. Is there?

in header of my layout I have

<meta name="csrf-token" content="{!! csrf_token() !!}">
<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
</script>

then in my form I have this

        <form name="callback" ng-controller="callbackController" role="form" class="" enctype="multipart/form-data">
          {!! csrf_field() !!}
    ...
    ...
<button type="submit" class="btn btn-primary pull-right" ng-click="submit(callback.$valid)" ng-bind="submittext" ng-class="{ 'btn-danger': callback.name.$touched && callback.name.$invalid || callback.tel.$touched && callback.tel.$invalid, 'btn-success': callback.name.$touched && callback.name.$valid && callback.tel.$touched && callback.tel.$valid, }">Send</button>

    </form>



via Chebli Mohamed

How to upgrade Laravel 5.0.* to 5.2.* or later

My Application is built with Laravel version 5.0.35 and I want it to update to version 5.2.*

How can I do this?? Can I just replace '5.0.*' to '5.2.*' in composer.json file and then command composer update, will this work?? If not, then is there any way with which I can upgrade easily and automatically?? Please guide me step by step if possible...



via Chebli Mohamed

How to define a "Master Layout" in Laravel 5.1

I'm starting to use Laravel 5.1 from 4.2 and I have a question about the definition of layouts in the controller.

In 4.2 I have this

private $layout = 'layouts.master';

    public function showWelcome()
    {
        $this->layout->content =  View::make('home');
    }

So when the view load, in the

@yield('section')

of the "master.blade.php" in the layouts folder will appears the view "Home"

I search how to use this in 5.1 and I see that the asignation of the layout.masters as been removed, but I can't see the new usage anywhere.

Now in 5.1 I have

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use View;

class HomeController extends BaseController {

    public function showWelcome()
    {
        return view('home');
    }
}

How Can I say to the function showWelcome that it have to yield the content with the view?

Sorry for my bad english.



via Chebli Mohamed

Laravel 5.1 Find an item using eloquent

I have following tables.

Users

id

name

Events

id

name

Cards

id

name

Transfers

id

event_id

card_id

An user has many events and cards. An user can accepts cards from other user which he met at an event.A row will be added under transfers table whenever a card is accepted by a user, this row links a card_id with event_id. I am looking for a way to check a card (card_id) is added under the transfers table for a logged in user's event(event_id).

eg:-

auth()->user()->events->transfers->where(([['card_id', '=',$cardid]])->find());

Can someone help me by telling what is the best way to handle above situation using eloquent?



via Chebli Mohamed

Laravel 5.1 loginUsingId() with linkedin account (using socialite) failed in Authenticate middleware

I'm using Laravel 5.1 and try implements login with LinkedIn to my app. The OAuth 2 login process working fine and I manage to add a new user to users table with the correct details. I can manage to log this user in using Laravel loginUsingId() function as well (i can see \Auth::user() after it) but it fails in the Authenticate middleware.

This is the providerExecute function in my AuthController:

 public function providerExecute($provider, Request $request, $token)
{
    if(!is_null($token)){
        session(['invitation_token' => $token]);
    }
    if (!$request->has('code')) {
        return $this->getAuthFirst($provider);
    }
    $user = Socialite::with($provider)->user();
    if ($user) {
        $pid = $user->id;
        $exists = User::where('email', $user->email)->first();
        if ($exists) {
            Auth::loginUsingId((int)$exists->id,true); //when dd() the \Auth::user() here - it's returns the user data
            return redirect('home');
        }
        $new_user = new User();
        if (session('invitation_token')) {
            $invitation = $this->getUserInvitation(session('invitation_token'));
            if(!is_null($invitation->client_id)){
                $client = Client::findOrFail($invitation->client_id);
                if(!$this->canAddUsers($client)){
                    Log::info('Register from invitation! Client ' . $client->name . ' reached max users count, client id: ' . $client->id);
                    return response()->view('errors.auth',
                        ['error' => 'Error! Reached users limit, to add more users please upgrade your account plan']);
                }
            }
            $new_user->client_id = $invitation->client_id;
            $new_user->agency_id = $invitation->agency_id;
            $new_user->auth_level = $invitation->auth_level;
            $invitation->active = 0;
            $invitation->save();
            $redirect_path = "verification/send/";
        }else{
            $new_user->auth_level = config('LM2.ADMIN_AUTH_LEVEL');
            $redirect_path = "welcome/send/";
        }
        $new_user->name = $user->name;
        $new_user->email = $user->email;
        $new_user->provider_id = $user->id;
        $new_user->provider_token = $user->token;
        $new_user->img_src = $user->avatar ? $user->avatar : $this->getDefaultAvatarSrc();
        $new_user->account_verified = 1;
        $new_user->save();
        Auth::loginUsingId($new_user->id);
        return redirect($redirect_path.$new_user->id);
    }else{
        abort('403' , 'Unauthorized.');
    }
}

And this is the Authenticate middleware:

public function __construct(Guard $auth)
{
    $this->auth = $auth;
}


public function handle($request, Closure $next)
{
    //When dd($this->auth->user()) - returns null;
    if (!$this->auth->user()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login') ;
        }
    }elseif(!$this->auth->user()->active){
        $this->auth->logout();
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login')->withErrors(['Inactive User']);
        }
    }

    return $next($request);
}

Anyone know the reason it's happans and what can be the solution for it? thank's a lot!



via Chebli Mohamed

Laravel Autocomplete not working

I have implemented a Laravel 5.1 autocomplete function using following codes:

snippet js

<script type="text/javascript"> 
 $(document).ready(function () {
  $("#utente").autocomplete({
    minLength:3,
    autoFocus: true,
    source: '',
    select: function( event, ui ) {
        window.location.href = ui.item.url;
    },

});
});

</script>

This is my Route:

Route::any('utente', function(){


 $term = Input::get('utente');
 // 4: check if any matches found in the database table 
 $data = DB::table("tb_users")->distinct()->where('last_name', 'LIKE', $term.'%')->groupBy('last_name')->get();
 foreach ($data as $v) {
 $nome = $v->last_name . ' ' . $v->first_name;
 $url = "clienti?utente=$v->id";
 $return_array[] = array('value' => $nome, 'label' => $nome, 'url' => $url);  }
  // if matches found it first create the array of the result and then convert it to json format so that 
  // it can be processed in the autocomplete script
 return Response::json($return_array);
 });

And this is the fiedl used for rendere the autocomplete.

<input type="text" id="utente" name="utente" placeholder="Cognome e Nome" class="form-control-utente" ></input>

The problem is that this fetch all the results in DB... and not the results that match the query



via Chebli Mohamed

dimanche 11 septembre 2016

Laravel excel export - string formatted column showing as number

In localhost i can set the column format as PHPExcel_Cell_DataType::TYPE_STRING and its working fine here is the .xls file by using this type

enter image description here

how ever if i test this in live i get something like enter image description here

column values set to 0.

Why i have tried PHPExcel_Cell_DataType::TYPE_STRING format is because the string like 65081035703021 showing as number (base 10) in ms-excel

Whats goes wrong for me?

enter image description here



via Chebli Mohamed