vendredi 2 décembre 2016

Laravel Broadcast Pusher Event Firing Multiple Times

I have this Laravel 5.1 Event that I fire when a chat is stored. But it is creating multiple broadcasts to Pusher

<?php namespace App\Events;

use App\Events\Event;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;

class ChatSent extends Event implements ShouldBroadcast
{
    use SerializesModels;

    public $channel;
    public $chat;

    public function __construct($channel,$chat)
    {
        $this->channel = $channel;
        $this->chat = $chat;
    }

    public function broadcastOn()
    {
        return ['private-'.$this->channel];
    }
}

I am using Supervisor (supervisord) with multiple workers... not sure if that makes a difference... here's the laravel.conf:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/app/artisan queue:work database --sleep=3 --tries=3 --daemon
autostart=true
autorestart=true
user=ubuntu
numprocs=8
redirect_stderr=true
stdout_logfile=/var/www/app/worker.log

Any idea why this may be happening?



via Chebli Mohamed

With query Issue in Eloquent

I have following query which works fine and gives result for StatusType

AddOnModel::with('StatusType')->get();

But when I write below, it does not bind StatusType Records

AddOnModel
::select(\DB::Raw('A.AddOnID, A.AddOn, Count(R.AddOnID) as Total'))
->from( 'tblAddOn as A' )
->with('StatusType')
->leftjoin( 'tblrevenue as R', \DB::raw( 'R.AddOnID' ), '=', \DB::raw( 'A.AddOnID' ) )
->groupBy("A.AddOnID", "A.AddOn")->get();

The part which does not work is this one: ->with('StatusType')

Am I doing something incorrectly?



via Chebli Mohamed

jeudi 1 décembre 2016

laravel 5.1 access-control-origin for restFull api

Guys I'm developing restFull api using laravel 5.1.My endpoints are working correctly on postman. But when I integrate it with front-end it is getting following error.

XMLHttpRequest cannot load http://ift.tt/2gFV6Wq. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ideahubfront.dev' is therefore not allowed access. The response had HTTP status code 500.

I've tried following methods.

(1) created core middle-ware.

 <?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With');
    }
}

added it to kernal.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \App\Http\Middleware\Cors::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'web' => \App\Http\Middleware\VerifyCsrfToken::class,
        'cors' => \App\Http\Middleware\Cors::class,
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    ];
}

and to routes.php

Route::group(['middleware' => ['web', 'core'], 'prefix' => 'api/v1'], function(){

    // get single user by user id
    Route::get('getuserbyid/{user_id}', 'UserController@getSingleUserById');

    Route::post('users/register', 'UserController@register');

});

After that options requests worked. But post request still same.

(2) Added headers to controller return manually. Like this.

return response()->json([$user, $merchant], 200)
                ->header('Access-Control-Allow-Origin', '*')
                ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
                ->header('Access-Control-Allow-Headers', 'Cache-Control, Connection, Date, Server, Content-Type, User-Agent,  Accept, Referer, Authorization,Origin,  Accept-Encoding, Content-Length, Host, Connection,  X-Requested-With');

No luck. Guys please help me. I'm dying for this. My clients wants to see the registration. I'm stuck on this.



via Chebli Mohamed

Task Scheduling : Laravel 5.3

I am following this tutorial to schedule a function every minute. Below is my code.

class Kernel extends ConsoleKernel
{
    protected $commands = [
        'App\Console\Commands\Inspire',
    ];

    protected function schedule(Schedule $schedule)
    {
        $schedule->call($this->WriteFile())->everyMinute();
    }

    protected function commands()
    {
        require base_path('routes/console.php');
    }

    private function WriteFile() {
        $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
        $txt = "John Doe\n";
        fwrite($myfile, $txt);
        fclose($myfile);
    }
}

I saw that the txt file is not showing the contents. i placed the txt file in public folder. Am I missing something?



via Chebli Mohamed

PayPal Express Checkout on behalf of a client php

I've received permissions for Express Checkout from my client using the Permissions Service, getting token and token-secret and I can generate the X-PAYPAL-AUTHORIZATION header [contains AccessToken, OAuthSignature, CurrentOAuthTimestamp] as described 'http://ift.tt/1payxXm'

I don't understand how can I call the SetExpressCheckout API on behalf of my client. I don't see the X-PAYPAL-AUTHORIZATION header mentioned in the Express Checkout docs. http://ift.tt/2gM3yUo



via Chebli Mohamed

Controller class not found laravel 5.1

I am new to laravel and I tried to post the values from view to controller. But I am not able to get through as i get error saying FatalErrorException in routes.php line 26: Class 'registration' not found while submitting the form

Routes.php

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

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

Route::post('/register_action', function()
{
     $values = registration::store();
});

Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\model\registration as register_model

class registration extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store()
    {
        echo 'hello';
        register_model::saveFormData();
    }
}

View

<html>
<head>
    <meta charset="UTF-8">
    <title>Registration</title>
</head>
<body>
    {!! Form::open(array('url' => 'register_action')) !!}
        <p>Name : {!! Form::text('name') !!}</p>
        <p>Email : {!! Form::text('email') !!}</p>
        <p>Password : {!! Form::password('password') !!}</p>
        <p>Confirm Password : {!! Form::password('cpassword') !!}</p>
        <p>{!! Form::submit('Submit') !!}</p>
    {!! Form::close() !!}
</body>
</html>

Please help me to solve the issue and to get the post values in controller. Thanks



via Chebli Mohamed

Update user profile in Laravel 5.1

I am trying to update some user profile data as follows:

To update profile in routes.php

Route::get('/profile/update/{id}', [
        'as' => 'user.edit',
        'uses' => 'UserController@edit'
    ]);

In my UserController.php

public function edit($id)
{
      $user = User::findOrFail($id);

      return view('user/edit', compact('user'));
}

My action in edit.blade.php

{!! Form::model($user, ['action' => ['UserController@update', 'id' => $user->id], 'method' => 'PUT']) !!}
                    <div class="form-group">
                        {!! Form::label('name', 'Name') !!}
                        {!! Form::text('name', $user->name, [
                            'class' => 'form-control'
                        ]) !!}
                    </div>

                    <div class="form-group">
                        {!! Form::label('email', 'E-mail') !!}
                        {!! Form::text('email', $user->email, [
                            'class' => 'form-control'
                        ]) !!}
                    </div>

                    <div class="form-group">
                        {!! Form::label('phone', 'Phone') !!}
                        {!! Form::text('phone', $user->phone, [
                            'class' => 'form-control'
                        ]) !!}
                    </div>

                    <p><button type="submit" class="btn btn-primary">Update Profile</button></p>
                {!! Form::close() !!}

The route for update:

Route::put('/profile/update/{id}', [
        'as' => 'user.update',
        'uses' => 'UserController@update'
    ]);

And the function in the UserController.php

public function update(Request $request, $id)
    {
        $user = User::findOrFail($id);
        $user->update([
            $request->input('name'),
            $request->input('email'),
            $request->input('phone')
        ]);

        return Redirect::route('user.profile');
    }

After updating the field I want (for example the phone), it simply returns to the profile screen, but does not update it in the database. What am I doing wrong? Thank you very much for your help.



via Chebli Mohamed