vendredi 31 août 2018

Laravel 5.1: Kbwebs\MultiAuth\Guard' does not have a method getAuthIdentifier

I am running Laravel 5.1 and am encountering the following error.

[2018-08-31 12:38:33] prod.ERROR: Debugbar exception: call_user_func_array() expects parameter 1 to be a valid callback, class 'Kbwebs\MultiAuth\Guard' does not have a method 'getAuthIdentifier' 

I am trying to display a user account with the following controller:

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {

        /** @var User $user */
        $user = Auth::user()->get();
        $transactions = $user->transactions()
            ->with('orders')
            ->where('type', '=', 'mealservice')
            ->whereIn('status', [Transaction::TRANSACTION_STATUS_DONE])
            ->orderBy('created_at', 'DESC')
            ->get();

        if ($transactions) {
            $moments = Moment::get();
            $meals = Meal::get();
        } else {
            $moments = collect();
            $meals = collect();
        }

        return view('website.pages.account.index')
            ->with(['transactions' => $transactions, 'user' => $user, 'userData' => $user->data]);
    }

I am able to get the user->data just fine. But once the view is triggered im encountering the above error. Does anyone have an idea?



via Chebli Mohamed

Change ways to retrieve user data - Password Broker - Laravel 5.1

First of all, sorry for my bad English

Currently I use PasswordBroker facade to reset password of users. Below is script to do:

use Password; // Facade: Illuminate\Auth\Passwords\PasswordBroker
...
...
$userCredentials = $request->only(
    'email', 'password', 'password_confirmation', 'token'
);

$response = Password::reset(
    $userCredentials,
    function (User $user, $password) {
        $user->password = $password;
        $user->save();
    }
);

With correct email, token and valid password, all users can reset their password easily.

New my system had been updated. All emails in users table has been encrypted (AES_ENCRYPT), so I need to make some changes to apply.

Here is getUser method of Password facade

public function getUser(array $credentials)
{
    $credentials = Arr::except($credentials, ['token']);

    $user = $this->users->retrieveByCredentials($credentials);

    if ($user && ! $user instanceof CanResetPasswordContract) {
        throw new UnexpectedValueException('User must implement CanResetPassword interface.');
    }

    return $user;
}

I need some where criteria like

$user->where(
    DB::raw("AES_DECRYPT(email, 'encryption key')"),
    $userEmail
);

How to apply the criteria without change original source code of Laravel?



via Chebli Mohamed

Provider Class not found in In ProviderRepository.php line 208

I have create a simple Laravel Package and pushed it on Github

https://github.com/akshaykhale1992/model-notes

and Published the Package on Packagist

https://packagist.org/packages/akshaykhale1992/model-note

I tried to install it in my laravel application, it pulled the package from Github but the package installation was not successful.

Below is the Error that is returned by composer command

root@root.com:~/$ composer require akshaykhale1992/model-note
Using version dev-master for akshaykhale1992/model-note
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing akshaykhale1992/model-note (dev-master 5543914): Cloning 554391487e from cache
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover

In ProviderRepository.php line 208:

  Class 'AkshayKhale1992\ModelNote\ModelNoteProvider' not found  


Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

Thanks in advance.

Terminal Screenshot enter image description here



via Chebli Mohamed

mardi 28 août 2018

RouteServiceProvider model bindings with OAuth2: accessing session data without token

I'm using Lucadegasperi's OAuth2 integration with Laravel 5.1.

I want to create a Tutorial instance, and want to simply pass the ID via the route from the client application, and have Laravel typehint it and auto-instantiate the model App\Tutorial for ID 1.

To do this, in my RouteServiceProvider's boot method, I bind the model:

public function boot(Router $router)
{
   parent::boot($router);
   $router->model('tutorial', 'App\Tutorial');
   ...
}

Which allows me to typehint and instantiate the tutorial model as {tutorial}:

$router->post('tutorials/{tutorial}/create', 'Resources\Tutorials@createManyToMany');

So when I call that route, which calls the Resources's createManyToMany method:

public function createManyToMany(Request $request, Route $route, Model $modelToAttach)
{
    // $modelToAttach of type Model will be auto-instantiated as App\Tutorial
    ...

The model will be good to go.

The issue is, I wrap these routes in Lucasdegasperi's OAuth2 middleware:

$router->group(['middleware' => 'oauth'], function(Router $router) {
    // routes

The server complains:

NoActiveAccessTokenException in Authorizer.php line 104:

Tried to access session data without an active access token



via Chebli Mohamed

Use OAuth middleware to get user inside Laravel model

I'm trying to eager load my Tutorials model with a where clause based on the logged in User's profile. I'm using Laravel 5.1 with Lucadegasperi's OAuth 2.

I want to find only the tutorials which belong to user profile ID 1. To do this, I first request an access token, then log the user into the application via DHC:

GET http://myapi.localhost/1.0/login
Headers: Authorization: Bearer xyZ... // valid token

Then make the request for the tutorials:

GET http://myapi.localhost/1.0/tutorials/1
Headers: Authorization: Bearer xyZ... // valid token

But the response says there's no valid token? Yet, when I perform login in AuthController.php, OAuth2 middleware's Authorizer::getResourceOwnerId() is able to locate the user. But in the Tutorial model, I get error:

NoActiveAccessTokenException in Authorizer.php line 104:

Tried to access session data without an active access token

AuthController.php:

...
public function login(Request $request)
{
    $user = User::find(Authorizer::getResourceOwnerId()); // Finds user

    if (!is_null($user)) {
        Auth::login($user);
        $request->session()->put('user', Auth::user());
        return $user;
    }

    return response()->json(['status' => 500, 'message' => 'Invalid email!']);
}
...

Tutorial Model:

use LucaDegasperi\OAuth2Server\Facades\Authorizer;
use Illuminate\Support\Facades\Auth;
use App\User;

class Tutorial extends BaseModel
{
     public function profiles()
     {
         $user = User::find(Authorizer::getResourceOwnerId()); // Throws error
         $user = Auth::user(); // Works fine

         return $this->belongsToMany(Profile::class, 'profile_tutorials')
             ->where('profile_id', '=', $user->profiles[0]->id)
             ->withPivot('view_count')
             ->withTimestamps();
     }
     ...
}

How can I use the OAuth middleware to get the user within a model?

Note: This works fine in the model when I use $user = Auth::user();, but don't see why I can't use the Authorizer.



via Chebli Mohamed

dimanche 26 août 2018

how can i get the week day in text from input date in laravel

<div class='col-md-2'> <div class='form-group'> {!! Form::label('date', 'Select Date')!!} {!! Form::input('datetime-local','date',Input::get('date'),['class'=>'form-control'])!!} </div> </div>

in the laravel controller are down, why it comes error

    $today=$request->date;

    $week_day=$today->format('l');

    dd($week_day);



via Chebli Mohamed

samedi 25 août 2018

get id of table in laravel using datatable

Hello friends I have two database table 1. Quotations 2. Clients

Issue 1 :

I have 4 entries in Quotations table

ID         customer_id      Exp_date
1            1               2018-08-24
2            1               2018-08-26
3            2               2018-08-24
4            2               2018-08-23

I want to fetch data where exp_date < 2018-08-25 but customer_id must be unique. In case any customer_id has exp_date > 2018-08-25 then this customer_id should not be fetched.

Currently I am using the following Query

$cur_date = date('Y-m-d');
   $clientTemp = DB::table('clients')->where('quotations.exp_date','<',$cur_date)
     ->join('quotations','quotations.customer_id','=','clients.id')
     ->groupBy('customer_id')
      ->get()
       ->map(function ($clientTemp) {
        return [
            'id' => $clientTemp->id,
            'hash' => $clientTemp->hash,
            'name' => $clientTemp->first_name.' '.$clientTemp->last_name,
            'email' => $clientTemp->email,
            'mobile' => $clientTemp->mobile
        ];
    });

It is returning the data of row ID 2 which Should Not be there.

Issue 2

I am fetching this data to data tables. I am using the following code :

return $datatables->collection($clientTemp)

        ->addColumn('actions', '@if(Sentinel::inRole(\'admin\'))
                                <a href="" title="">
                                        <i class="fa fa-fw fa-pencil text-warning "></i> </a>
                                @endif')

        ->removeColumn('id')
        ->rawColumns(['actions'])->make();

In addColumn a href code I am using variable $id where I want to show the id of clients table. currently it is showing the Id of quotations table.

Please help me to solve both the issues



via Chebli Mohamed