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

Distinct Values in Laravel

Hello Friends 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')
      ->get()
       ->map(function ($clientTemp) {
        return [
            'id' => $clientTemp->id,
            'hash' => $clientTemp->hash,
            'name' => $clientTemp->first_name.' '.$clientTemp->last_name,
            'email' => $clientTemp->email,
            'mobile' => $clientTemp->mobile
        ];
    });

I am getting this data from two tables :

1. Qutoations and 2. Clients.

In quotations table if the exp_date is less than current date then the details will be fetched from client table.

But there is possibility then there are more than 1 rows in quotation table but I want to fetch only one table from that for which customer_id is unique. How can I fetch unique row with same customer_id from quotations table



via Chebli Mohamed

jeudi 23 août 2018

laravel create multiple sessions

I am developing laravel 5.1 project.this is for backend and for the api. the api is used by several interfaces as following diagram(c1, c2).all these interfaces authenticated by this api.

enter image description here

those are differentiate with the parameters you send.that means for c1,

{"username":"user","password":"password","brand":"c1"}

and for c2,

{"username":"user","password":"password","brand":"c1"}

lets say a user has accounts with same identical information(same username and passwords are used on both platforms) on c1,c2 platform. so when authenticating this user on c1 with laravel's Auth::loginUsingId function it creates session. then if i try to log in c2, successfully login to c2. but automatically logs out from c1. for this matter i need to have multiple sessions in my project. how can I do this?



via Chebli Mohamed

Laravel sort by keys

I make an array with collections with code:

$hours = Voucher::where('created_at','>=', Carbon::now()->startOfMonth())->get()->groupBy(function($item)
{
  return $item->created_at->format('H');
});

dd($hours);

so I get data like this:

enter image description here

SO keys are hours (00-23).

How I can arrange it starting by 00, 01, 02, 03 ... ...



via Chebli Mohamed

mercredi 22 août 2018

How to run Laravel 5.3 ..?

i am using laravel 5.3, How to run welcome message

this is my web.php file

<?php
  Route::get('/', function () {
  return view('welcome');

});



via Chebli Mohamed

lundi 20 août 2018

why jpg file are saved as tmp in laravel 5.1

OK i'm new in Laravel and i need any help in my code. I'm trying to upload image in admin panel. but this image is uploading as tmp. Need i add something other code in my code?

public function store(Request $request)
{


    if ($request->hasFile('contents')) {


        $destinationPath = 'pictures/SliderImages';
        $files = $request->contents;
        $file_name = $files->getClientOriginalName();
        $files->move($destinationPath, $file_name);
        echo "Complete";
    } else {
        echo "No File";
    }


    $inputs = $request->all();

    $sliders = Sliders::Create($inputs);

    return redirect()->action('SliderController@index');
}

this is my blade

                @foreach($sliders as $slider)
                    <tr>
                <td></td>
                <td></td>
                <td><img src=""></td>
                    </tr>
                    @endforeach

this is result in phpmyadmin



via Chebli Mohamed

how to integrate wecashup payment in laravel5.1?

i want to integrate wecashup payment in my laravel5.1 project. I used https://www.wecashup.com , https://www.wecashup.com/dashboard/settings , https://www.wecashup.com/tutorials for this.



via Chebli Mohamed

mardi 14 août 2018

Best way to check if model returns results in laravel

I'm fairly new to laravel and looking for the best method for checking whether a model has returned any results or not.

The example below will return null if not results are found. Which is perfect if you only ever want the first result.

$results = FooBar::where(['col' => 'someVal', 'col3' => 'value'])->first();

The example below will return an object regardless of there being any results.

$results = FooBar::where(['col' => 'someVal', 'col3' => 'value'])->get();

Therefore i'm currently having to do this every time:

if($results && count($results)) {
     // then do stuff
}

I have methods that call various models and the code looks ugly and inefficient with all of these count() functions.

FYI I'm currently using laravel 5.1 due to our php version (not within my control).



via Chebli Mohamed

dimanche 12 août 2018

Optimize laravel project with extracting methods

I am working on a ongoing laravel project which uses laravel 5.1. There is a process that takes over 8 seconds. within that process, there is a method that has almost 250 lines of code.In optimization perspective, if I extracted that code into several methods, will it be faster than usual or will it take much time?



via Chebli Mohamed

vendredi 10 août 2018

App.css in laravel moves to previous state

Whenever I change something in app.css and then in app.scss and run non run development, all my changes in app.css file vanished and previous state of the file appeared. How to save the changes in app.css in laravel



via Chebli Mohamed

Ionic formData append showing null in server

I am trying to upload an image using formData. The api is working fine. But the data is displaying null in the server. My function is

  capture_dl_front(){
    this.camera.getPicture(this.cameraOptions)
      .then(imageData => {
        this.customer.dl_front = normalizeURL(imageData);
        this.upload_dl_front(imageData);
      }, error => {
        this.func.showAlert('Error',JSON.stringify(error));
      });
  }
  upload_dl_front(imageFileUri: any): void {
    this.file.resolveLocalFilesystemUrl(imageFileUri)
      .then(entry => (<FileEntry>entry).file(file => this.readFile_dl_front(file)))
      .catch(err => console.log('Error',JSON.stringify(err)));
  }
  private readFile_dl_front(file: any) {
    const reader = new FileReader();
    reader.onloadend = () => {
      const imgBlob = new Blob([reader.result], { type: file.type });
      this.dl_front_imageUri = imgBlob;
      this.dl_front_imageName = file.name;
      alert(this.dl_front_imageName)
      const img = new FormData();
      img.append('image', this.dl_front_imageUri, this.dl_front_imageName)
      this.api.test(img).then(data=>alert("final: "+data))
    };
    reader.readAsArrayBuffer(file);
  }

and my api function is

 test(image){
    let headers = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded',
    });
    return new Promise( resolve => {
      this.http.post(url, image, { headers: headers})
        .subscribe(
          data => {
            resolve(data['message']);
          },
          error => {
            resolve(error.statusText);
          }
        );
    });
  }

and i am getting the file in my laravel server as

$image = $request->file('image');

but i am getting null in the image parameter.

What am i doing wrong here?



via Chebli Mohamed

jeudi 9 août 2018

Add ID and Type from supplemental tables to parent table using SQL (MySQL & Laravel Polymorphic relations)

Note. Also posted on Database Administrators

I have one table that records all sales and fourteen supplemental tables which contain extra information about a sale. The fourteen supplemental tables are for all intents and purposes the same. They were created long ago when the initial developer thought there would be more differences but actually now that the project has matured they are more similar than they are different. They are different however, and as such I need to keep them separate.

Current structure

Sales table

| id      | customer_id | customer_ref                         | ... |
|---------|-------------|--------------------------------------|-----|
| 1237567 | 354         | a6143f8c-b679-47be-9bc0-52457842913c | ... |
| 1237568 | 867         | ref89b72                             | ... |
| ...     | ...         | ...                                  | ... |

Supplemental table 1 Class: App\SuppOne

| id   | customer_id | customer_ref                         | ... |
|------|-------------|--------------------------------------|-----|
| 2857 | 10372       | 2016-07-01-ab5d09cc37ca              | ... |
| 2858 | 354         | a6143f8c-b679-47be-9bc0-52457842913c | ... |
| ...  | ...         | ...                                  | ... |

Supplemental table 2 Class: App\SuppTwo

| id    | customer_id | customer_ref | ... |
|-------|-------------|--------------|-----|
| 90488 | 867         | ref89b72     | ... |
| 90489 | 1024        | 0000080992   | ... |
| ...   | ...         | ...          | ... |

There are no foreign keys on the tables to join the sales table to the supplemental tables but there is a 'customer_id' and 'customer_reference' which are unique to both the sales tables and also the supplemental tables but they are not consistent. This is what is currently used to join the two as-and-when I need to get more information about a given sale.

I'm using Laravel 5.1 and a MySQL database and I'd like to add two fields to the sales table; supplemental_id and supplemental_type in order to quickly and efficiently create a polymorphic relation.

Desired structure

Sales table

| id      | supplemental_id | supplemental_type | customer_id | customer_ref                         | ... |
|---------|-----------------|-------------------|-------------|--------------------------------------|-----|
| 1237567 | 2858            | App\SuppOne       | 354         | a6143f8c-b679-47be-9bc0-52457842913c | ... |
| 1237568 | 90488           | App\SuppTwo       | 867         | ref89b72                             | ... |
| ...     | ...             | ...               | ...         | ...                                  | ... |

I need to add these two fields to each of the sales records but I am unsure how to do this with raw SQL as I expect it would be much quicker than if done in a migration. I'd like to know how (if possible) in SQL, do I deal with the mapping from table_name to App\ClassName. There are about 1.5m records in the sales table and looping over them all will not take an insignificant amount of time.



via Chebli Mohamed

vendredi 3 août 2018

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'products.all_category' doesn't exist (SQL: select * from `all_countries`)

 'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
    'mysql2' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST_2', '127.0.0.1'),
        'port' => env('DB_PORT_2', '3306'),
        'database' => env('DB_DATABASE_2', 'forge'),
        'username' => env('DB_USERNAME_2', 'forge'),
        'password' => env('DB_PASSWORD_2', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

products is the default database and all_category is the table name in second database called category it is not even identifying the second database category ,it is only taking the first default one while configuring ,here is the query inside controller:-

$users = DB::connection('mysql2')->table("all_category")->get(); 

Any help would be much appreciate, Thanks in advance



via Chebli Mohamed

mercredi 1 août 2018

Laravel (1/1) NotFoundHttpException in RouteCollection.php line 179

I've encountered a problem submitting my form in laravel. My form structure looks this.

<form  class="form-group" action="" 
method="post" name="publish" enctype="multipart/form-data"  
onsubmit="return validateForm();">
   <input type="text" name="user">
   <textarea name="poem"></textarea>
   <input type="submit" value="save">
</form>

My web.php file has this route.

Route::post('/writepoem', ['uses'=>'PoemController@postCreatePoem','as'=>'writepoem']);

My PoemController.

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Poem;

class PoemController extends Controller
{ 
    public function postCreatePoem(Request $request)
    {   
        //validation
        $poem=new Poem();
        $poem->poem=$request['poem'];
        $poem->poem=$request['user'];



        //save poem
        $request->user()->poems()->save($poem);
        return redirect()->route('feed');
    }
}

On submitting my form I get this Exception.

(1/1) NotFoundHttpException

in RouteCollection.php line 179.

What could be the issue with routing?



via Chebli Mohamed