mardi 31 octobre 2017

Guzzle Error - cURL error 6: Couldn't resolve host

Description

If I have this in my class

class CURL {

public static function get($url) {

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1000);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //<------ Note HERE 
    curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    $result =  json_decode($result, true);
    return $result;

}

My page load fine.

enter image description here


If I have this in my class

<?php
namespace App;

use Request,Auth;
use App\Log, App\Helper;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;



class CURL {

    public static function get($url) {

        $client = new Client();
        $result = $client->request('GET',$url, ['http_errors' => false, 'verify' => false ]);
        $result = (string) $result->getBody();
        $result = json_decode($result, true);
        return $result;

    }
    ...

}

As you can see, I tried set 'verify' => false already.

My page show this error.

enter image description here


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

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



via Chebli Mohamed

Laravel 5 if statement between Carbon diffForHumans and toFormattedDatesString

I want to write an if statement to show timestamp in diffForHumans format for timestamps less than less than 5 days old and in toFormattedDatesString for anything older than that.

For example today is 31/10/17, so timestamp for 28/10/2017 should show - 3 days ago and timestamp for 20/10/2017 should show Oct 20, 2017.

Can someone please tell any logic to achieve this? Thanks in advance for the help.



via Chebli Mohamed

dimanche 29 octobre 2017

How to get full url of image after amazon s3 upload

I need to get full url of a image which is uploaded to amazon s3. I tried following functions. I am using laravel 5.1.

Storage::disk("s3")->url($filename);
Storage::url($filename);
Storage::temporaryUrl('file1.jpg', Carbon::now()->addMinutes(5));
$filesystem->getAdapter()->getClient()->getObjectUrl($bucket, $key);

all are showing undefined function url (or) temporaryUrl (or) getObjectUrl.



via Chebli Mohamed

samedi 28 octobre 2017

How to place a range in the model::list method for combo in laravel?

I would like you to help me, to solve my question, and I would like to know what is the way to range my combo of charges, which comes from the database in the description field, but It list all the records , and I just need to show some of them, so I need to know how to set a range for the mentioned combo, This is where my combo is that gives me all the charges that are registered in the database, to pass them to a View to a select tag:

//VIEW TO REGISTER USERS
  public function VistaRegistraUsuario()
{

  $id_franquicia_usuario = Session::get('id_franquicia');
  $charges = charges_users::lists('descripcion', 'id'); //COMBO OF CHARGES

  return view('auth.register', compact('charges', 'id_franquicia_usuario'));
}// END VIEW



via Chebli Mohamed

laravel 5.1 check if a session is expired

I'm working on a laravel 5.1 application and I want to check if a user session has expired after each request, in order to redirect the user to the login page. in order to do so I have created a middleware that runs on every request, the handle function looks like this

public function handle($request, Closure $next)
{
     if(session_status() === PHP_SESSION_NONE)
     {
          return redirect()->guest('login');
     }
     return $next($request);
}

this does not seem to work correctly, because when I type 'localhost:8000' in google chrome it says 'localhost redirected you too many times', I guess it is because the session have not been started since the user is not logged in, so... is there any better way to do this checking?



via Chebli Mohamed

vendredi 27 octobre 2017

Laravel 5.1: migrate command doesn't work 'unknown database'

Good day!

I am facing problems with my laravel project built with laravel 5.1.

So I developed a reservation system with laravel, it works on my local server.

Then I uploaded it to my live server and started an SSH session.

But when I ran php artisan migrate command, this error showed up

[PDOException] SQLSTATE[HY000] [2005] Unknown MySQL server host 'sddb0040291787.cgidb' (0)

So, what I did so far is I wrote a php script to create the tables and other database related stuff and then run the php script on my server.

This works actually, my CRUD functions are working but I know this is just a temporary solution.

What I am looking for is a permanent solution. Plain PHP scripts seem to be able to connect to the database host. but when I migrate using laravel, the error always shows up. Any ideas?



via Chebli Mohamed

jeudi 26 octobre 2017

Rewriting laravel 5.1 controller action route on the Request object

I have many modules my source code organized into subfolders inside the App\Http\Controllers e.g App\Http\Controllers\ModuleOne.

The base controllers are in App\Http\Controllers and the module controllers extend these base controllers. A module controller might not exist if I don't want to customize the base controller when using that particular module.

I want to write a logic where a route checks if the module controller exists. If the route does not exist, it should route the action to a BaseController.

I have tried to make a middleware and other solutions but can't seem to get this done.

I want to have the routing inside all the controllers done with the same name (thus ignoring the module name - which will be defined by an env variable). So, to simplify code I want to call:

Route::get('apple','AppleController@view')

and from this route it should check if:

App\Http\Controller\module1\module1_AppleController.php

exists.

If it does, use it. If not, it should route to the base controller action i.e. App\Http\Controller\AppleController.

Can't seem to figure out where to do this with efficient code. Can the rewrite be done in RouteServiceProvider in middleware or other?

Also, if the newer version of Laravel could present a solution not found in 5.1, I am willing to upgrade, so don't limit answers to 5.1.



via Chebli Mohamed

Laravel 5.1. cannnot run artisan commands

I am using Laravel 5.1 and I cannot run any artisan commands.

I uploaded my project to our live server with PHP5.5.22 CLI version.

everytime I run artisan commands I am getting this error SQLSTATE[HY000] [2003] Can't connect to MySQL server on '127.0.0.1' (146)

I changed the configuration on my .env and config/database.php files to point to our MySQL server.

.env file

DB_CONNECTION=mysql
DB_HOST=****.sddb0040291787.*****
DB_PORT=3306
DB_DATABASE=sddb0040291787
DB_USERNAME=sddbMTcyNjEy
DB_PASSWORD=**********

config/database.php

'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', '****.sddb0040291787.*****'),
        'database'  => env('DB_DATABASE', 'sddb0040291787'),
        'username'  => env('DB_USERNAME', 'sddbMTcyNjEy'),
        'password'  => env('DB_PASSWORD', '**********'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

even php artisan config:cache command doesn't work and returns same error.

Appreciate any help. Thanks guys!



via Chebli Mohamed

mardi 24 octobre 2017

Are there altenatives for Redis - spiritix/lada-cache in the Laravel 5.1 framework

We have a laravel 5.1 app that we set up to use Redis, along with spiritix/lada-cache. We went this route because it gave really good performance on App Engine. Then, during testing one of our users complained that items were missing on a page whereas they showed up on another page. When we ran the same code with a remote connection to the same db we didn't get the same results. This led us to consider that lada-cache was an issue. We flushed the cache and could then see the same data from different the different pages.

Subsequent net searches brought us to this: Queries build by Eloquent\Builder instead of Query\Builder and this:Eloquent Models not updating / flushing Cache correctly. Both huge issues (assuming there hasn't been a fix).

First, are there any alternatives aside from Laravel's out of the box memcache which is not so fast? Second, if Redis is the way to go, are there any go arounds that we can use that bypass the above issues?



via Chebli Mohamed

laravel download excel file from s3 is not working

I am using laravel 5.1 I need to download excel from amazon s3 storage. I done all process correctly and if it is pdf format file means it downloading correctly but for excel file download it is downloading zip format. Can please anyone help me to fix this issue.

$filePath = "CIS/download/format/upload_format.xlsx";
if ( Storage::disk('s3')->has($filePath)) {
$file = Storage::disk('s3')->get($filePath);
$getMimeType = Storage::disk('s3')->getMimetype($filePath);
return Response::make($file, 200, [
'Content-Type' => $getMimeType,
'Content-Disposition' => 'attachement; 
filename:upload_format.xlsx',
]);
}



via Chebli Mohamed

lundi 23 octobre 2017

cURL error 28: Operation timed out after 2000 milliseconds with 7276200 out of 23000995 bytes received

Description

I'm using Guzzle in my Laravel project. I had a memory crash when I make a request to an API that return a huge payload.

I have this on the top of my CURL.php class. I have get() that I use guzzle.

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
use GuzzleHttp\FORCE_IP_RESOLVE;
use GuzzleHttp\DECODE_CONTENT;
use GuzzleHttp\CONNECT_TIMEOUT;
use GuzzleHttp\READ_TIMEOUT;
use GuzzleHttp\TIMEOUT;

class CURL {

    public static function get($url) {

        $client = new Client();
        $options = [
            'http_errors' => true,
            'force_ip_resolve' => 'v4',
            'connect_timeout' => 2,
            'read_timeout' => 2,
            'timeout' => 2,
        ];
        $result = $client->request('GET',$url,$options);
        $result = (string) $result->getBody();
        $result = json_decode($result, true);
        return $result;

    }

    ...

}

When I call it like this in my application, it request a large payload (30000)

$url = 'http://site/api/account/30000';
$response =  CURL::get($url)['data'];

I kept getting this error

cURL error 28: Operation timed out after 2000 milliseconds with 7276200 out of 23000995 bytes received (see http://ift.tt/1mgwZgQ)

How do I avoid this?


Should I increase these settings?

'connect_timeout' => 2,
'read_timeout' => 2,
'timeout' => 2,


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

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



via Chebli Mohamed

Set preference for Laravel 5.1 Queues

I am using laravel 5.1 for my application. And for event handlers i am using shoudque as below

class QuizCreatedHandler implements ShouldQueue
{
   /**
     * Create the event listener.
     *
     * @return void
     */
     public function __construct()
     {
     }

  /**
    * Handle the event.
    *
    * @param  QuizCreated  $event
    * @return void
   */
    public function handle(QuizCreated $event)
    {
       //codes here
    }
}

But the thing when i comment shouldqueue, events working perfectly. But if i use shouldqueue, the event is not getting even after 1 hour. Is there any way to check it? Or is there any way to set high priority to this queue ?

Appreciate any Help.



via Chebli Mohamed

Laravel excel import date format issue in windows

I am using laravel 5.1 I need to import excel to process some data. I have to process date which is entered in excel. For ubuntu os its working fine. For windows os date column interchanging while loading the excel. For example If I upload excel with date 20-11-2017 means the loaded value will be 11-20-2017 it is wrong. Can please anyone help me to fix this issue. My code given below. I am using "maatwebsite/excel": "~2.0.0".

Excel::load($file, function($reader) {
        $details = $reader->formatDates(true)->toArray();
    });



via Chebli Mohamed

samedi 21 octobre 2017

Laravel data is not saving in user table .and also not going postRegister function. please help me

am registering use through Auth controller (the auth controller use use AuthenticatesAndRegistersUsers, ThrottlesLogins). when is click on register function it go

use toAuthenticatesAndRegistersUsers 

then authcontroller but not going in postRegister. :( also not showing any error.please help me. here is AuthController

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Models\Employee;
use App\Role;
use Validator;
use Illuminate\Support\Facades\Hash;
use Eloquent;
use Mail; 
use Session;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }

    public function showRegistrationForm()
    {
        $roleCount = Role::count();
        if($roleCount != 0) {
            $userCount = User::count();
            if($userCount == 0) {
                return view('auth.register');
            } else {
                return redirect('login');
            }
        } else {
            return view('errors.error', [
                'title' => 'Migration not completed',
                'message' => 'Please run command <code>php artisan db:seed</code> to generate required table data.',
            ]);
        }
    }
       public function showLoginForm()
        {
            $roleCount = Role::count();
            if($roleCount != 0) {
                $userCount = User::count();
                if($userCount == 0) {
                    return redirect('register');
                } else {
                    return view('auth.login');
                }
            } else {
                return view('errors.error', [
                    'title' => 'Migration not completed',
                    'message' => 'Please run command <code>php artisan db:seed</code> to generate required table data.',
                ]);
            }
        }

        /**
         * Get a validator for an incoming registration request.
         *
         * @param  array  $data
         * @return \Illuminate\Contracts\Validation\Validator
         */
        protected function validator(array $data)
        {
            return Validator::make($data, [
                'name' => 'required|max:255',
                'email' => 'required|email|max:255',
                'password' => 'required|min:6|confirmed',
            ]);
        }

        /**
         * Create a new user instance after a valid registration.
         *
         * @param  array  $data
         * @return User
         */
        protected function create(array $data)
        {
            // TODO: This is Not Standard. Need to find alternative
            Eloquent::unguard();

            $employee = Employee::create([
                'name' => $data['name'],
                'designation' => "Admin",
                'mobile' => "85888",
                'mobile2' => "",
                'email' => $data['email'],
                'gender' => 'Male',
                'dept' => "1",
                'city' => "Lahore",
                'address' => "Pakistan",
                'about' => "About user / biography",
                'date_birth' => date("Y-m-d"),
                'date_hire' => date("Y-m-d"), 
                'date_left' => date("Y-m-d"),
                'salary_cur' => 0,
            ]);

            $user = User::create([
                'name' => $data['name'],
                 'firstname' => $data['firstname'],
                  'lastname' => $data['lastname'],
                   'address' => $data['address'],
                    'mobile_number' => $data['mobile_number'],
                     'deals' => $data['deals'],
                       'city_id' => $data['city_id'],
                         'plaza_id' => $data['plaza_id'],
                'email' => $data['email'],
                 'pin_code'=>date('U'),
                'password' => Hash::make($data['password']),
                'context_id' => $employee->id,
                'type' => "ADMIN",
            ]);
            $role = Role::where('name', 'ADMIN')->first();
            $user->attachRole($role);
                 //  email for  Shop Owner
            Mail::send('emails.email', ['user' => $user], function ($m) use ($user) {
             //   $m->from('hello@app.com', 'Your Application');

              $m->to($user->email,$user->name)->subject('Welcome at Classified!');
           });

    // email for administration
        /* Mail::send('emails.email', ['user' => $user], function ($m) use ($user) {
             //   $m->from('hello@app.com', 'Your Application');

              $m->to($user->email,$user->name)->subject('Welcome at Classified!');
           });
    */

         Session::flash('success', "Your request has been sent for verification by Master Networks !!!");

            return $user;
        }
    }

here is may route

Route::get('/registers', 'Frontend\RegisterController@index');
    Route::post('/registers', 'Auth\AuthController@postRegister');

here is RedirectsUsers

<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
trait RegistersUsers
{
    use RedirectsUsers;

    /**
     * Show the application registration form.
     *
     * @return \Illuminate\Http\Response
     */
    public function getRegister()
    {
        return $this->showRegistrationForm();
    }

    /**
     * Show the application registration form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showRegistrationForm()
    {
        if (property_exists($this, 'registerView')) {
            return view($this->registerView);
        }

        return view('auth.register');
    }

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postRegister(Request $request)
    {

        return $this->register($request);
    }

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = $this->validator($request->all());

        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }

        Auth::guard($this->getGuard())->login($this->create($request->all()));

        return redirect($this->redirectPath());
    }

    /**
     * Get the guard to be used during registration.
     *
     * @return string|null
     */
    protected function getGuard()
    {
        return property_exists($this, 'guard') ? $this->guard : null;
    }
}



via Chebli Mohamed

vendredi 20 octobre 2017

Laravel use dynamic mutators in where clause

So i have two columns - SizeX & SizeY. For front end users I use Laravel mutator

public function getSizeAttribute(){
    /**
     * Set Size
     */
    $size = $this->SizeX. " x ". $this->SizeY;
    /**
     * Return
     */
    return $size;
}

To format the sizes like this SizeX x SizeY. The column Sizes does not exists because its dynamic. Is it possible to use mutators or alternative within the Elaquent model to detect that this is a dynamic attribute, and use some sort of method to convert the SizeX x SizeY to individual columns? Once the user submits the attribute Size back to laravel application for filtering?

Edit:

Right, this is the method I'm using to retrieve filtered Items

public function scopeFilteredMaterials($query,$params = array()){ 
    /**
     * Get filters
     */
    $filters = array();
    /**
     * Extract Info
     */
    if(!empty($params) && is_array($params)){
        /**
         * Get Available Filters
         */
        $filters = $this->getAvailableFilters();

        foreach ($filters as $key => $filter){
            if(isset($params[$filter])){

                $filters[$filter] = $params[$filter];

                unset($filters[$key]);
            }else{

                unset($filters[$key]);
            }
        }
    }

    foreach ($filters as $key => $filter){

        $query->whereIn(key ,$filter);
    }

    $result = $query->get();
}

This is the filters variable which holds available filters for user to see

protected $filters = array( "Name", "url", "Size", );

I'm using the above to show the specific values to the user. Once the user selects those values I'm using the same array to check against those filters and fire the query. My problem is the Size attribute is made up of two columns which I have not problem using the following Mutator and $appends variable to automatically bring the value to the user.

/**
 * Get Size Attribute
 */
public function getSizeAttribute(){
    /**
     * Set Size
     */
    $size = $this->SizeX. " x ". $this->SizeY;
    /**
     * Return
     */
    return $size;
}

But i ca't figure out a way to convert the Size variable back to SizeX & SizeY



via Chebli Mohamed

jeudi 19 octobre 2017

Laravel avoid running out of memory

Im trying to use laravel excel to create an excel sheet. Because my database is expanding the memory limit is reached and I get the error:

FatalErrorException in Connection.php line 321: Allowed memory size of 134217728 bytes exhausted (tried to allocate 196605 bytes)

I already raised the memory limit a few times but I would like to improve the function so it uses less memory so I dont need to raise the memory limit everytime. I already use chuncking to try and lower the memory using but to no avail.

My function:

public function exportExcel($year)
{

    $datum = date("d-m-Y");


    Excel::create('Sales export '.$datum, function($excel)use($year) {


        $datum = date("d-m-Y");

        // Chain the setters
        $excel->setCreator('author name')
            ->setCompany('company name')
            ->setDescription('sales export.')
            ->setTitle('sales export '.$datum);

        $excel->sheet('sales '.$datum, function($sheet)use ($year) {

            $sheet->appendRow(array(
                "merk","product","artikel nr","afbeelding","categorie","collectie","maat","omschrijving","inkoopprijs","verkoopprijs","prijs betaald","aantal verkocht","verkocht aan",  "totaal","dag","maand","jaar","kwartaal","reseller","verkoper","bestel naam", "status"
            ));
            Order::whereYear('created_at', '=', $year)->orderBy('billed_at','desc')->chunk(1, function($orders)use ($sheet){
                foreach($orders as $index => $order)
                {

                    foreach($order->products as $p)
                    {

                        $sizeLink = $p->productSize;
                        $productLink = $sizeLink->product;


                        // Append row as very last
                        $sheet->appendRow(array(
                            //Merknaam  Artikelnr.  Soort   Kleur   Maat
                            //Omschrijving  Geboekt aantal  Basiseenheid
                            //inkoopprijs   verkoopprijs    aant stuks verkocht
                            //Maand Jaar    Kwartaal


                            $productLink->brand->name, //merknaam
                            $productLink->name, //productnaam
                            $productLink->artnr, //Artikelnr
                            //link naar de hoofdafbeelding
                            "". URL::to('/'). ucfirst($productLink->mainthumb),
                            $productLink->category->name, //soort
                            $productLink->collection->name, //soort
                            $sizeLink->size->name,   //maat naam
                            $productLink->desciption,   //omschrijving
                            number_format((float) $productLink->price_buy_in, 2, ',', ''), //inkoopprijs
                            number_format((float) $productLink->price, 2, ',', ''), //verkoopprijs
                            number_format((float) $p->price, 2, ',', ''), //prijs betaald
                            $p->quantity, //geboekt aantal
                            $order->billingname . $order->billingnamelast, //verkocht aan
                            number_format((float) $p->quantity * $p->price, 2, ',', ''), // totaal kosten
                            //number_format((float) ($p->quantity * $p->price - $p->quantity * $p->price_buy_in), 2, ',', ''), // winst inkoop-verkoop
                            date("d",strtotime($order->billed_at)), //dag
                            date("n",strtotime($order->billed_at)), //maand
                            date("Y",strtotime($order->billed_at)), //jaar
                            ceil(date("m",strtotime($order->billed_at))/3), // kwartaal
                            $order->reseller->name, // verkoper
                            $order->creator, // verkoper
                            $order->name, //text op factuur
                            $order->status->name,
                        ));
                    }
                }

            });


            // Auto filter for entire sheet
            $sheet->setAutoFilter();
            $sheet->freezeFirstRow();
            // Set black background
            $sheet->row(1, function($row) {

                // call cell manipulation methods
                $row->setBackground('#cccccc');
                $row->setFontWeight("bold");

            });
    $sheet->setColumnFormat(array(
        'G' =>  \PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00,
        'H' => '[$EUR ]#,##0.00_-',
        'I' =>  \PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00,
    ));

        });

    })->download('xlsx');;
}

I know I could raise the memory limit but I would like to find out why so much memory is used and how I can avoid using to much memory.



via Chebli Mohamed

Laravel Form Input hidden keep returning empty

Description

I have a form

<form method="POST" accept-charset="UTF-8" action="http://site/account/1003/destroy">
  <input name="_method" type="hidden" value="DELETE">
  <input name="_token" type="hidden" value="pBRx8u17C6KHFxzfhatx0BpnmOF5x55EWSP2lpis">
  <input name="id" type="hidden" value="1003">
  <a data-dismiss="modal" class="btn btn-danger mr10">No</a>
  <button type="submit" class="btn btn-success" data-toggle="modal" data-target=".bs-example-modal-lg"> Yes </button>
</form>

As you can see the id has the value of 1003.


Attempt

I'ved to test in my destroy() function

public function destroy($id)
{
    dd(Input::all());
    ...

I got

array:3 [▼
  "_method" => "DELETE"
  "_token" => "pBRx8u17C6KHFxzfhatx0BpnmOF5x55EWSP2lpis"
  "id" => "" <------ empty 
]

I double check everything. I could not seem to know what is the cause of my id to be empty while I can clearly see it in the HTML in my browser.


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

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



via Chebli Mohamed

joining tables in laravel and get data by group

I have tables like below. I want to get the data which has count of unique make_id.

I joined all the tables and I'm getting error as 'Unexpected data found'.

leads:

+----+------------+
| id | vehicle_id |
+----+------------+
| 1  |     1      |
| 2  |     2      |
| 3  |     3      |
+----+------------+

vehicles

+----+------------+
| id | model_id   |
+----+------------+
| 1  |     1      |
| 2  |     2      |
| 3  |     3      |
+----+------------+

models:

+----+------------+
| id | make_id    |
+----+------------+
| 1  |     1      |
| 2  |     2      |
| 3  |     3      |
+----+------------+

This is my code:

$Leads = Leads::join('vehicles', 'vehicles.id', '=', 'leads.vehicle_id')
        ->join('models', 'models.id', '=', 'vehicles.model_id')
->groupBy('vehicles.model_id')
->get();

Thank you



via Chebli Mohamed

mercredi 18 octobre 2017

Make a GET with Guzzle in Laravel 5.1

I have an API, and make GET to it via Postmen

Ex.http://site/api/users.count

I got

{
    "status": 200,
    "message": "Success",
    "data": {
        "count": 8
    }
}

I've tried to use Guzzle

composer require guzzlehttp/guzzle  


Using version ^6.3 for guzzlehttp/guzzle                                                                                          
./composer.json has been updated                                                                                                  
Loading composer repositories with package information                                                                            
Updating dependencies (including require-dev)                                                                                     
  - Installing guzzlehttp/promises (v1.3.1)                                                                                       
    Downloading: 100%                                                                                                             

  - Installing psr/http-message (1.0.1)                                                                                           
    Loading from cache                                                                                                            

  - Installing guzzlehttp/psr7 (1.4.2)                                                                                            
    Loading from cache                                                                                                            

  - Installing guzzlehttp/guzzle (6.3.0)                                                                                          
    Downloading: 100%                                                                                                             

Writing lock file                                                                                                                 
Generating autoload files                                                                                                         
> php artisan clear-compiled                                                                                                      

> php artisan optimize                                                                                                            

Generating optimized class loader                                                                                                 


include it

I add these 2 lines on top of my class

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;


use it

$client = new Client();
$res = $client->request('GET','http://site/api/users.count');
dd($res);


result

I kept getting

Response {#664 ▼
  -reasonPhrase: "OK"
  -statusCode: 200
  -headers: array:4 [▼
    "Connection" => array:1 [▼
      0 => "Keep-Alive"
    ]
    "Content-Length" => array:1 [▼
      0 => "61"
    ]
    "Content-Type" => array:1 [▼
      0 => "application/json; charset=utf-8"
    ]
    "Date" => array:1 [▼
      0 => "Wed, 18 Oct 2017 18:01:50 GMT"
    ]
  ]
  -headerNames: array:4 [▼
    "connection" => "Connection"
    "content-length" => "Content-Length"
    "content-type" => "Content-Type"
    "date" => "Date"
  ]
  -protocol: "1.1"
  -stream: Stream {#662 ▼
    -stream: stream resource @272 ▼
      wrapper_type: "PHP"
      stream_type: "TEMP"
      mode: "w+b"
      unread_bytes: 0
      seekable: true
      uri: "php://temp"
      options: []
    }
    -size: null
    -seekable: true
    -readable: true
    -writable: true
    -uri: "php://temp"
    -customMetadata: []
  }
}


expected result

I am hoping to get a similar result like this :

{
    "status": 200,
    "message": "Success",
    "data": {
        "count": 8
    }
}


question

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

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



via Chebli Mohamed

Laravel 5.1 MethodNotAllowedHttpException - Registration

I have a problem with registration. When the user will finish registration then he will get this error message - MethodNotAllowedHttpException in RouteCollection.php line 219. Could you check pls the code if you will the issue that causing this error.

01.) Routes.php

/**
     * Guest only visit this section
     */
    Route::group(['middleware' => 'guest'], function () {
        Route::get('account/login', ['as' => 'login', 'uses' => 'Auth\LoginController@getLogin']);
        Route::get('auth/{provider}', 'Auth\LoginController@getSocial');
        Route::get('auth/{provider}/callback', 'Auth\LoginController@getSocialCallback');
        Route::get('registration/{provider}', 'Auth\RegistrationController@getSocialRegister');
        Route::get('account/registration', ['as' => 'registration', 'uses' => 'Auth\RegistrationController@getIndex']);
        Route::get('registration/activate/{username}/{code}', 'Auth\RegistrationController@validateUser');
        Route::get('password/email', ['as' => 'password.reminder', 'uses' => 'Auth\PasswordController@getEmail']);
        Route::get('password/reset/{token}', 'Auth\PasswordController@getReset');
    });

    /**
     * Guest Post form with csrf protection
     */
    Route::group(['middleware' => 'csrf:guest'], function () {
        Route::post('account/login', 'Auth\LoginController@postLogin');
        Route::post('registration/{provider}', 'Auth\RegistrationController@postSocialRegister');
        Route::post('password/email', 'Auth\PasswordController@postEmail');
        Route::post('password/reset/{token}', 'Auth\PasswordController@postReset');
        Route::post('account/registration', 'Auth\RegistrationController@postIndex');
        Route::get('image/freefiles/{slug}', ['as' => 'images.freefiles', 'uses' => 'ImageController@getFreeFiles']);
    });

02.) login.blade.php

   <form action="" method="POST">
                                    <input type="hidden" name="_token" value="">
                                    <div class="sminputs">
                                        <div class="input full">
                                            <label class="string optional" for="username">username*</label>
                                            <input class="string optional" maxlength="255" id="username" name="username" placeholder="username" type="text" size="50" />
                                        </div>
                                    </div>
                                    <div class="sminputs">
                                        <div class="input full">
                                            <label class="string optional" for="email">Email*</label>
                                            <input class="string optional" maxlength="255" id="email" name="email" placeholder="Email" type="email" size="50" />
                                        </div>
                                    </div>
                                    <div class="sminputs">
                                        <div class="input string optional">
                                            <label class="string optional" for="password">Password *</label>

                                            {!! Form::password('password',['class'=>'form-control input-lg','placeholder'=>t('Enter Password'),'autocomplete'=>'off','required'=>'required']) !!}
                                        </div>
                                        <div class="input string optional">
                                            <label class="string optional" for="password_confirmation">Repeat password *</label>

                                            {!! Form::password('password_confirmation',['class'=>'form-control input-lg','placeholder'=>'Confirm Password','autocomplete'=>'off','required'=>'required']) !!}
                                        </div>
                                    </div>
                                    <div class="simform__actions">
                                        <input class="sumbit" name="commit" type="submit" value="Create Account" />

                                        <span class="simform__actions-sidetext">By creating an account you agree to our <a class="special" href="#" target="_blank" role="link">Terms & Privacy</a></span>
                                    </div>
                                </form>

03.) login_beta.blade.php

  <form action="" class="contact_form2" method="POST">
            <h1 style="text-align: center">Create Your Account</h1>
            <input type="hidden" name="_token" value="">
            <ul id="usn_eml">
                <li>
                    <input type="text" maxlength="255" id="username" name="username" class="textbox1"
                    placeholder="Your username..." required/>
                    <span class="form_hint">Enter username</span>
                </li>
                <li>
                    <input type="email" maxlength="255" id="email" name="email" class="textbox1"
                    placeholder="Your email..." required>
                    <span class="form_hint">Enter email...</span>
                </li>
                <li>
                    {!! Form::password('password',['class'=>'textbox1','placeholder'=>t('Enter Password'),'autocomplete'=>'off','required'=>'required']) !!}
                    <span class="form_hint">Your password...</span>
                </li>
                <li>
                    {!! Form::password('password_confirmation',['class'=>'textbox1','placeholder'=>'Confirm Password','autocomplete'=>'off','required'=>'required']) !!}
                    <span class="form_hint">Confirm password...</span>
                </li>
                                <ol style="clear: both; display: block; padding-top: 17px;">
               
                <div class="form-group">
                    <script src='http://ift.tt/1xQsaAf'></script>

                    <div class="g-recaptcha" data-sitekey="xxxx"></div>
                </div>
            
                           </ol>
                <input name="commit" type="submit" value="Create Account"/>
                
            </ul>

            <style>
                #usn_eml {
                    width: 50%;
                    display: block;
                    margin: auto;
                }
            </style>

            

            <div class="tos">
                By creating an account you agree to our <a
                class="special" href="http://ift.tt/2ywFks0" target="_blank" role="link">Terms &
                Privacy</a>
            </div>

            <div class="already_member">
                <p>Already a member? Please<a id="getSignInDiv" href="#"> Sign In</a></p>
            </div>
        </form>


via Chebli Mohamed

Payfort integration Response in Laravel 5.1

I am using payfort as payment gateway. And y application is in Laravel 5.1. Iam using a pafort library for integrating it. When i am using purchase request api, it returns a html page.

When i check it in postman, for pretty, got response something like

 <!DOCTYPE html>
 <html>
<head>
    <title>Payment redirect page</title>
</head>
<body>
    <form method="post" action="http://ift.tt/2bOOvZK" id="frm" name="frm">
        <input type="hidden" name="command" value="PURCHASE">
        <input type="hidden" name="access_code" value="hjwuuquudhqdjd">
        <input type="hidden" name="merchant_identifier" value="klklkns">
        <input type="hidden" name="merchant_reference" value="ijijisux">
        <input type="hidden" name="amount" value="1000">
        <input type="hidden" name="currency" value="USD">
        <input type="hidden" name="language" value="en">
        <input type="hidden" name="customer_email" value="dev@gmail.com">
        <input type="hidden" name="return_url" value="http://ift.tt/2yyvTsA">
        <input type="hidden" name="signature" value="70ff4d91adef50f91c049bc68b64c12d1b212d5597463c3a2fef30830aa502dc">

    </form>
    <script>
document.frm.submit();
  </script>
 </body>
</html>

But for preview, i got a blank page. What should i do? I couldnt proceed without getting that preview.



via Chebli Mohamed

How to filter a tree like array by a specific field using Laravel Eloquent

This is my result tree which I want to filter by 'language_code' field

"theme_detail": [
            {
                "id": 1,
                "parent_theme_id": null,
                "image_url": "no_image",
                "index_value": 1,
                "status": "active",
                "theme_detail": [
                    {
                        "id": 4,
                        "theme_id": 1,
                        "language_code": "bn",
                        "theme_name": "থিম 1",
                        "theme_subtitle": "থিম 1 উপশিরোনাম",
                        "status": "active"
                    },
                    {
                        "id": 1,
                        "theme_id": 1,
                        "language_code": "en",
                        "theme_name": "Theme 1",
                        "theme_subtitle": "Theme 1 Subtitle",
                        "status": "active"
                    }
                ],
                "parent_recursive": [
                    {
                        "id": 2,
                        "parent_theme_id": 1,
                        "image_url": "no_image",
                        "index_value": 1,
                        "status": "active",
                        "theme_detail": [
                            {
                                "id": 5,
                                "theme_id": 2,
                                "language_code": "bn",
                                "theme_name": "থিম 2",
                                "theme_subtitle": "থিম 2 উপশিরোনাম",
                                "status": "active"
                            },
                            {
                                "id": 2,
                                "theme_id": 2,
                                "language_code": "en",
                                "theme_name": "Theme 2",
                                "theme_subtitle": "Theme 2 Subtitle",
                                "status": "active"
                            }
                        ],
                        "parent_recursive": [
                            {
                                "id": 3,
                                "parent_theme_id": 2,
                                "image_url": "no_image",
                                "index_value": 1,
                                "status": "active",
                                "theme_detail": [
                                    {
                                        "id": 3,
                                        "theme_id": 3,
                                        "language_code": "en",
                                        "theme_name": "Theme 3",
                                        "theme_subtitle": "Theme 3 Subtitle",
                                        "status": "active"
                                    },
                                    {
                                        "id": 6,
                                        "theme_id": 3,
                                        "language_code": "bn",
                                        "theme_name": "থিম 3",
                                        "theme_subtitle": "থিম 3 উপশিরোনাম",
                                        "status": "active"
                                    }
                                ],
                                "parent_recursive": [
                                    {
                                        "id": 4,
                                        "parent_theme_id": 3,
                                        "image_url": "no_image",
                                        "index_value": 1,
                                        "status": "active",
                                        "theme_detail": [
                                            {
                                                "id": 7,
                                                "theme_id": 4,
                                                "language_code": "bn",
                                                "theme_name": "থিম 4",
                                                "theme_subtitle": "থিম 4 উপশিরোনাম",
                                                "status": "active"
                                            },
                                            {
                                                "id": 9,
                                                "theme_id": 4,
                                                "language_code": "en",
                                                "theme_name": "Theme 4",
                                                "theme_subtitle": "Theme 4 Subtitle",
                                                "status": "active"
                                            }
                                        ],
                                        "parent_recursive": []
                                    }
                                ]
                            },
                            {
                                "id": 5,
                                "parent_theme_id": 2,
                                "image_url": "no_image",
                                "index_value": 1,
                                "status": "active",
                                "theme_detail": [
                                    {
                                        "id": 8,
                                        "theme_id": 5,
                                        "language_code": "bn",
                                        "theme_name": "থিম 5",
                                        "theme_subtitle": "থিম 5 উপশিরোনাম",
                                        "status": "active"
                                    },
                                    {
                                        "id": 10,
                                        "theme_id": 5,
                                        "language_code": "en",
                                        "theme_name": "Theme 5",
                                        "theme_subtitle": "Theme 5 Subtitle",
                                        "status": "active"
                                    }
                                ],
                                "parent_recursive": []
                            }
                        ]
                    }
                ]
            }
        ]


This is my json array which is in a tree like structure. This array is the result of a recursive eloquent relation. Now I want to filter it by a specific language code or by any other field. How can I do it using Laravel eloquent? can anybody help?



via Chebli Mohamed

How to make a date/time count like facebook (3days ago, etc)

I'm a newbie in php, and offcourse I'm a newbie in laravel. Anyway, 've got a problem. In some documentations, people uses "diffForHuman". Unfortunately I always get error 500 when I use it. I want to do a count of date/time like facebook, ex : "3days ago", etc.

this is my controller :

    public function show(Request $request)
{
 if($request->ajax()){
        $searchs = $request->get('search');
        $search = $searchs['value'];
        \DB::statement(\DB::raw('set @nomor = 0'));

        $index = DB::table('tb_jabatan_karyawan')
                ->leftJoin('tb_jabatan','tb_jabatan.id','=','tb_jabatan_karyawan.id_jabatan')
                ->leftJoin('tb_karyawan','tb_karyawan.id','=','tb_jabatan_karyawan.id_karyawan')
                ->select([
                    \DB::raw('@nomor := @nomor + 1 as no'),

                    'tb_jabatan_karyawan.id as id',
                    'tb_jabatan_karyawan.id_karyawan as id_karyawan',
                    'tb_jabatan_karyawan.id_jabatan as id_jabatan',
                    'tb_karyawan.nama as nama',
                    'tb_karyawan.status_karyawan as status',
                    'tb_jabatan.nama_jabatan as jabatan',
                    'tb_karyawan.tgl_masuk as lama'
                    ]);
            //dd(Carbon::parse($index->lama)->diffForHumans());
        return Datatables::of($index)
            ->edit_column('no', function($index){
                return '<center>'.$index->no.'</center>';
            })
            ->edit_column('nama', function($index){
                return ucwords($index->nama);
            })
            ->edit_column('status', function($index){
                return ucwords($index->status);
            })
            ->editColumn('lama', function ($index) {
            return $index->lama->diffForHumans();
            })
            ->filter(function ($query) use ($request){
                if ($request->get('search')['value']){
                  $query->where('nama', 'like', "%{$request->get('search')['value']}%");
                }
            })
            ->addColumn('action', function($index){
                $tag = "<center><a class='btn btn-info btn-xs' onclick=atur('".$index->id_karyawan."','".$index->id_jabatan."')><i class='fa fa-pencil'></i> Proses</a></center>";
                return $tag;
            })
        ->make(true);
    }

}

and this is my datatable :

    function getData(){
table = $('#table').DataTable({
    dom: "lBfrtip",
    processing: true,
    serverSide: true,
    destroy: true,
    bFilter:true,
    searching: true,
    order: [],
    ajax: base_adm+'kelola/pengunduran-karyawan/show',

    columns: [
        {data: 'no', name: 'no', orderable: true, searchable: false},
        {data: 'nama', name: 'nama', orderable: true, searchable: true},
        {data: 'status', name: 'status', orderable: true, searchable: false},
        {data: 'jabatan', name: 'jabatan', orderable: true, searchable: false},
        {data: 'lama', name: 'lama', orderable: true, searchable: false},
        {data: 'action', name: 'action', orderable: false, searchable: false},
    ],
      "language": {
        "lengthMenu": " _MENU_  Baris",
        "zeroRecords": "Data Tidak Tersedia",
        "info": "Halaman _PAGE_ Dari _PAGES_",
        "infoEmpty": "Data Tidak Tersedia",
        "infoFiltered": "(Hasil penyaringan dari _MAX_ total data)",
        "sSearch": "Pencarian ",
        "oPaginate": {
        "sNext" : "Selanjutnya",
        "sPrevious" : "Sebelumnya",
    },
    },
});

}

I hope someone will help me to fix this. thank's anyway



via Chebli Mohamed

mardi 17 octobre 2017

Laravel 5.3 - Authentication is broken

About a year ago we took over an existing Laravel 5.1 site and upgraded to 5.3 - We recently became aware that an admin panel that was part of the old site no longer works (or unable to authenticate).

The original routes file contains the following:

//Login
 Route::controllers([
     'auth' => 'Auth\AuthController',
     'password' => 'Auth\PasswordController',
 ]);
//Admin
//Dashboard
Route::group(array('prefix' => 'admin', 'middleware' => 'auth'), function() {

    //Dashboard
    Route::get('/webadmin', array('as' => 'dashboard', 'uses' => 'Admin\DashboardController@index'));

});

Which after the upgrade stopped working as I understand the Route::controllers method was depreciated. We changed it to the following as I understand that was the replacement:

//Login
Route::resource('password','Auth\PasswordController');
Route::resource('auth','Auth\LoginController');
//Admin
//Dashboard
Route::group(array('prefix' => 'admin', 'middleware' => 'auth'), function() {

    //Dashboard
    Route::get('/webadmin', array('as' => 'dashboard', 'uses' => 'Admin\DashboardController@index'));
});

However, when we access the sites admin panel by http://ift.tt/2yp8ycW we are automatically redirect to example.com/login which then displays the dreadful NotFoundHttpException in compiled.php

This leads me to believe that the authentication middleware is not registered correctly. I am not sure what the correctly route is to take so will gladly appreciate any assistance :)



via Chebli Mohamed

Menu controller is not found laravel 5.5.check my code please and help me where am wrong

check my code please and help me where am wrong. am try to get date from Menu and SubMenu table using Eloquent model instead of join etc. my Menucontroller

class MenuController extends Controller
{
// Where ever you want your menu
    public function menu()
    {

        $menu = Menu::all()->load('submenu');

        return view('menu',['users' => $menu]);
    }
}

my menu Model is

use Illuminate\Database\Eloquent\Model;
class Menu extends Model
{


    public function submenu()
    {
        return $this->hasMany(SubMenu::class);
    }
}

my submenu model is

use Illuminate\Database\Eloquent\Model;
class SubMenu extends Model
{
    public function menu()
    {
        return $this->belongsTo(Menu::class);
    }
}



via Chebli Mohamed

Package egeloen/http-adapter is abandoned, you should avoid using it, How to fix on composer update

I'm using a PHP Laravel website on a Ubuntu server,

Package egeloen/http-adapter is abandoned, you should avoid using it. Use php-ht
tp/httplug instead.

the above message appears when I try to run composer update. I also tried composer require egeloen/http-adapter , but it shows new error massage now as follows.

Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages.

Problem 1 - infusionsoft/php-sdk 1.2.2 requires egeloen/http-adapter ~0.6 -> no matchi
ng package found. - infusionsoft/php-sdk 1.2.2 requires egeloen/http-adapter ~0.6 -> no matchi
ng package found. - infusionsoft/php-sdk 1.2.2 requires egeloen/http-adapter ~0.6 -> no matchi
ng package found. - Installation request for infusionsoft/php-sdk == 1.2.2.0 -> satisfiable by
infusionsoft/php-sdk[1.2.2].

I'm new for these things,Thank You



via Chebli Mohamed

FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found

            PaymentController.php 

            <?php 
            namespace App\Http\Controllers;
            use Paypalpayment;
            class paymentController extends Controller 
            {
                private $_apiContext;
                function __construct()
                {
                    $this->_apiContext = Paypalpayment::apiContext(config('paypal_payment.Account.ClientId'
                    ), config('paypal_payment.Account.ClientSecret'));

                }
                public function store()
                {
                    $addr= Paypalpayment::address();
                    $addr->setLine1("3909 Witmer Road");
                    $addr->setLine2("Niagara Falls");
                    $addr->setCity("Niagara Falls");
                    $addr->setState("NY");
                    $addr->setPostalCode("14305");
                    $addr->setCountryCode("US");
                    $addr->setPhone("716-298-1822");
                    $card = Paypalpayment::creditCard();
                    $card->setType("visa")
                        ->setNumber("4758411877817150")
                        ->setExpireMonth("05")
                        ->setExpireYear("2019")
                        ->setCvv2("456")
                        ->setFirstName("Joe")
                        ->setLastName("Shopper");
                    $fi = Paypalpayment::fundingInstrument();
                    $fi->setCreditCard($card);
                    $payer = Paypalpayment::payer();
                    $payer->setPaymentMethod("credit_card")
                        ->setFundingInstruments(array($fi));
                        $item1 = Paypalpayment::item();
                    $item1->setName('Ground Coffee 40 oz')
                            ->setDescription('Ground Coffee 40 oz')
                            ->setCurrency('USD')
                            ->setQuantity(1)
                            ->setTax(0.3)
                            ->setPrice(7.50);
                    $item2 = Paypalpayment::item();
                    $item2->setName('Granola bars')
                            ->setDescription('Granola Bars with Peanuts')
                            ->setCurrency('USD')
                            ->setQuantity(5)
                            ->setTax(0.2)
                            ->setPrice(2);
                    $itemList = Paypalpayment::itemList();
                    $itemList->setItems(array($item1,$item2));
                    $details = Paypalpayment::details();
                    $details->setShipping("1.2")
                            ->setTax("1.3")
                            //total of items prices
                            ->setSubtotal("17.5");

                    //Payment Amount
                    $amount = Paypalpayment::amount();
                    $amount->setCurrency("USD")
                            // the total is $17.8 = (16 + 0.6) * 1 ( of quantity) + 1.2 ( of Shipping).
                            ->setTotal("20")
                            ->setDetails($details);


                    $transaction = Paypalpayment::transaction();
                    $transaction->setAmount($amount)
                        ->setItemList($itemList)
                        ->setDescription("Payment description")
                        ->setInvoiceNumber(uniqid());



                    $payment = Paypalpayment::payment();

                    $payment->setIntent("sale")
                        ->setPayer($payer)
                        ->setTransactions(array($transaction));
                        try
                     {

                       $payment->create($this->_apiContext);
                          }
                     catch (\PPConnectionException $ex) 
                     {
                        return  "Exception: " . $ex->getMessage() . PHP_EOL;
                        exit(1);
                    }

                    dd($payment);
                } 
            }

            ?>

        Composer.json 
        {
            "name": "laravel/laravel",
            "description": "The Laravel Framework.",
            "keywords": ["framework", "laravel"],
            "license": "MIT",
            "type": "project",
            "require": {
                "php": ">=5.5.9",
                "laravel/framework": "5.1.*"
                 "laravelcollective/html": "5.1.*"
               "anouar/paypalpayment" : "~1.0"
            },
            "require-dev": {
                "fzaninotto/faker": "~1.4",
                "mockery/mockery": "0.9.*",
                "phpunit/phpunit": "~4.0",
                "phpspec/phpspec": "~2.1"
            },


        FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found
        i m getting this error FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found


        FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found
        i m getting this error FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found
    FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found
        i m getting this error FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found
FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found
        i m getting this error FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found
    FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found
        i m getting this error FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found

FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found i m getting this error FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found i m getting this error FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found i m getting this error FatalErrorException: Class 'anouar\Paypalpayment\PaypalpaymentServiceProvider' not found



via Chebli Mohamed

lundi 16 octobre 2017

¿How to capture a value from a select in the login view and declare it global?

I can not manage to capture a value from a combo from my login view, to use it in the user registry. I am trying to use the HTTP routes methods as described in the laravel 5.1 documentation, but without any success.

Here is the combo cboFranquicias in the view of login.blade.php, whose value I want to capture to pass it to the user registry view:

<form method="POST" action="">
    {!! csrf_field() !!}
    <div class="row margin">
      <div class="input-field col s12">
    <i class="mdi-social-person-outline prefix"></i>
    <input type="text" name="usuario" id="usuario" value="" required>
    <label for="usuario" class="center-align">Usuario</label>
    </div>
  </div>
  <div class="row margin">
    <div class="input-field col s12">
      <i class="mdi-action-lock-outline prefix"></i>
      <input type="password" name="password" id="password" required>
      <label for="password">Contraseña</label>
    </div>
  </div>

 <!--COMBO TO LIST FRANQUICIAS -->
   <br><div class="input-field col m12 s12" style="right:-1%">
    {!!Form::select('Franquicias', $combo_franquicias, null, ['placeholder'=>'--Selecciona--','id'=>'cboFranquicias','name'=>'cboFranquicias'])!!} 
    {!!Form::label('Franquicias')!!}
  </div><!--END COMBO -->


  <div class="row">
      <!--ACOMODADO TAMAÑO DEl BOTON ENTRAR-->
    <div class="input-field col s12 m12">
      <button type="submit" class="btn waves-effect waves-light col s12 m12 19">Entrar</button>
    </div>
  </div>
</form>

Later, in routes.php, I declare a route that takes by the method the values entered in the login, to the function that will return the user registry view:

Route::get('registrar', 'Auth\AuthController@VistaRegistraUsuario'); Route::post('auth/login', 'Auth\AuthController@VistaRegistraUsuario');

And here is the function that returns to the user registry view in the AuthController.php file:

`public function VistaRegistraUsuario(Request $request)
  {
 $id_franquicia = $request->input('cboFranquicias');
 //dd($id_franquicia);
 $cargos = cargos_usuarios::lists('descripcion', 'id');

 return view('auth.register', compact('cargos','id_franquicia'));
  }`

However, the value never reaches the user registry view, which should pass to fill my hidden input in that view register.blade.php:

{!!Form::input('Id_franquicia', $id_franquicia, null, ['type'=>'hidden','name'=>'id_franquicia', 'id'=>'id_franquicia'])!!}

How do I capture the value of the franquicias combo in the login view and save it to a global variable, to pass that value to the user registration view?



via Chebli Mohamed

samedi 14 octobre 2017

Cancel a running Laravel job

Because of long running jobs (~3hrs, multiple jobs, cannot just cancel all of them), I am attempting to stop/cancel a single running Laravel job.

The job class is prepared and sent to the queue with $this->dispatch($job).

Using database for the queue driver with supervisor installed, which was setup as stated in the Laravel documentation.

Any help in the right direction would be appreciated, thanks.



via Chebli Mohamed

vendredi 13 octobre 2017

Email Sending Using IBM Notes in Laravel

Good day.

I was tasked to send an email using IBM Notes. I am using Laravel and hardly know where to start. I have some basic knowledge about sending email using gmail but not with IBM Notes email.

Any help would be appreciated. Thanks.



via Chebli Mohamed

Change imported file encoding in Laravel


After a deep research in the forum, I am posting my problem here, because no topic matched my situation.
I am importing a file(csv or excel) in Laravel, in my controller I am using Input::file('file_name') to get the file.
The user has to possibility to choose his encoding from a select in the interface.
So my problem, is that I want to change the file encoding, to that set by the user.
I used mb_detect_encoding function but I always if I check after, I have the ASCII encoding always...
Here my code:

$encoding = Input::get('encoding');
$importFile = Input::file('import_file');
$enc = mb_detect_encoding($importFile, mb_list_encodings(), true);
if ($enc !== $encoding){
    file_put_contents($importFile->getClientOriginalName(),mb_convert_encoding(\File::get($importFile), $encoding, $enc));
}

Thanks in advance



via Chebli Mohamed

jeudi 12 octobre 2017

welcome.blade.php not working in laravel

In my fresh laravel project, I create a authentication pages using

php artisan make:auth

Then I rename

welcome.blade.php to welcome1.blade.php

and replace new

welcome.blade.php

file. refresh page. But still shows old page view in browser. Not new one. I change text in welcome1.blade.php. But view not changed.

plase help me. How replace new file.



via Chebli Mohamed

How to pass parameter from controller to model in case of recursion

My Theme Model

class Theme extends Model
{
    protected $fillable = [
        'level','parent_theme_id','image_url','index_value','status',
    ];
    protected $hidden =[
         'created_at','updated_at','updated_by','created_by',
    ];

       public function themeDetail()
    {
        return $this->hasMany(ThemeDetail::class,'theme_id');
    }

    public function parentTheme()
    {
        return $this->hasMany(Theme::class,'parent_theme_id');
    }

    public function childTheme()
    {
        return $this->belongsTo(Theme::class,'parent_theme_id');
    }

    public function childrenRecursive()
    {
       return $this->childTheme()->with('childrenRecursive');

    }

    public function parentRecursive($request)
    {
       return $this->parentTheme()->with(['themeDetail' => function($query) use($request){
        $query->whereIn('language_code',array('en',$request->language_code));
       }])->parentRecursive($request);
    }

 }


My themeDetail Model

class ThemeDetail extends Model
{
    protected $fillable = [
        'theme_id','language_code','theme_name','theme_subtitle','status',
    ];
    protected $hidden =[
         'created_at','updated_at','updated_by','created_by',
    ];

        public function theme()
    {
        return $this->belongsTo(Theme::class);
    }
}


And My Theme Controller

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Theme;

class ThemeController extends Controller
{
    public function theme(Request $request){
        $theme_detail = Theme::with(['themeDetail' => function($query) use($request){
            $query->whereIn('language_code',array('en',$request->language_code));
        },**'parentRecursive'**])->whereNull('parent_theme_id')->get();
        if($theme_detail->isNotEmpty()){
            return response()->json(['status' => 'success','message' => 'Theme List with Detail','theme_detail' => $theme_detail], 200);
        }else{
            return response()->json(['status' => 'not-found','message' => 'Theme List with Detail'], 205);
        }

    }

}


Here I have used a recursive relation for fetching theme and subthemes in a tree like structure.

Now I want to send a parameter '$request->language_code' through the parentRecursive relation (which is highlighted in my query) of Theme controller to parentRecursive relation of Theme model.

So, what is the correct syntax to pass the parameter from controller to model for this case? Please Help.



via Chebli Mohamed

mercredi 11 octobre 2017

How to set laravel excel password protection to open

I am using laravel 5.1. I need to export details as excel format with password protect to open the file. Can anyone please help me how to do this. I am using "maatwebsite/excel": "~2.1.0" plugin.



via Chebli Mohamed

laravel excel download with password protected not working

By using "maatwebsite/excel": "~2.1.0" version, I want to get the excel password protected. Find the code which I've tried, but it is gone unattained. I need password protect while opening file.

Excel::create`enter code here`($excelName, function($excel) 
use($exportData) {
$excel->sheet('sheet', function($sheet)  use($exportData) {
$sheet->getProtection()->setSheet(true);
$sheet->getProtection()->setSort(true);
$sheet->getProtection()->setInsertRows(true);
$sheet->getProtection()->setFormatCells(true);
$sheet->getProtection()->setPassword('password');
$sheet->fromArray($exportData);
});

})->export('xls');



via Chebli Mohamed

mardi 10 octobre 2017

Laravel Query behave differently on IPv4 Vs. IPv6 Environment

I have a weird situation here that I never seen before while using Laravel. I have the same code base on different set up, 1 in IPv4 VM, 1 in IPv6 VM.

This is the data in the database. This is how I normally query it.

$gw = Gateway::where('cpe_mac','=',$ap)->first();
dd($gw);

In my IPv4 Set up, I got :

{#541 ▼
  +"id": 1
  +"account_id": "50"
  +"cpe_mac": "102030405067"
  +"gw_id": "1956692524588882"
  +"gw_secret": "zUIyaQfCntob2thL6uR4uQfBvmlCei-5q_oVSJnyeSc"
  +"fb_wifi_enable": "1"
  +"created_at": "2017-10-10 14:41:17"
  +"updated_at": "2017-10-10 14:41:17"
}

In my IPv6 Set up, I got :

null

The most confusing part is, other tables seems to work fine, this gateways seems to be the only one that causing the problem.

I triple checked my Gateway model name, and table name. They spelled correclty.


  • Have you guys seen something like this before ?

  • How would one go about and debug this issue further ?

  • What else should I try ?



via Chebli Mohamed

Laravel command - Only optional argument

I have a command with this signature

order:check {--order}

And execute this:

php artisan order:check --order 7

For some reason that results in this exception

  [RuntimeException]                                 
  Too many arguments, expected arguments "command".  

Why? I want that this command can either be executed as php artisan order:check or with an optional order id php artisan order:check --order X



via Chebli Mohamed

i don't know how to install or use VentureCraft/revisionable

am new. so do not know how to use or install. any one can help me to install VentureCraft/revisionable. thanks in advance.



via Chebli Mohamed

dimanche 8 octobre 2017

Get array of event listeners

How can I get the array of event listensers that I have specified in the EventServiceProvider?

    protected $listen = [
    'App\Events\PaymentWasCompleted' => [
        'App\Listeners\GenerateInvoice',
    ]
];

Is there a "laravel" way to do that?



via Chebli Mohamed

Laravel elequent many to many and polymorphic relarion

I have a user , role, role_user and a photo(Polymorphic ) model class and related table in db. I i am using many to many relationship for role and user in user model i use a trait( using "use HasRoles"):

HasRoles

    trait HasRoles
{

    /**
     * A user may have multiple roles.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    /**
     * Assign the given role to the user.
     *
     * @param  string $role
     * @return mixed
     */
    public function assignRole($role)
    {
        return $this->roles()->save(
            Role::whereName($role)->firstOrFail()
        );
    }

    /**
     * Determine if the user has the given role.
     *
     * @param  mixed $role
     * @return boolean
     */
    public function hasRole($role)
    {

        if (is_string($role)) {

            return $this->roles->contains('name', $role);
        }

        return !! $role->intersect($this->roles)->count();
    }
}

User controller :

 public function __construct(User $user)
    {

        $this->middleware('auth');

        $this->user = $user;

    }

    /**
     * $userList and $dataArr from  Erp\Lists\UserList containing the array and the model to pass
     * for creating dynamic lists
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(UserList $list)
    {
        $usersList =$list;
        $model = $this->user;
        $users = $this->user->paginate(5);

        $usersWithPhotos = array();
        foreach($users as $user){

            if( !$user->hasRole('Teacher')
                && !$user->hasRole('Student')
                && !$user->hasRole('Guardian')
                && count($user->photos)>0)

                $usersWithPhotos[$user->photos->last()->name] = $user;
        }

and view:

@foreach($usersWithPhotos as $photo => $user)



                                                <tr>
                                                <td></td>

                                                <td class="text-center">{!!  Html::image('imagecache/dummy/'.$photo) !!}</td>
                                                
                                                <td class="text-center">
                                                    @if(!is_null($user->translate($defaultLocale)))

                                                        
                                                    @else

                                                        No Name Given in ...@if($locale=='en') English @else  Bangla @endif
                                                    @endif

                                <div class="pagination">{!!   str_replace('/?','?',$users->render() ) !!} </div>

What i want:

i want to get all users except role "student and teacher, and guardian" and also want use pagination with the result. now i am using two eloquent . one for pagination and another for get correct user list. also check if the user has photo in photos table. The problem is that i got the user list but pagination got long(1,2,3,4,----) for one user list. how can i get correct list with pagination?



via Chebli Mohamed

vendredi 6 octobre 2017

Mongodb string to date conversion

Below is my sample mongodb collection

{
    "_id" : ObjectId("57ed32f4070577ec56a56b9f"),
    "log_id" : "180308",
    "issue_id" : "108850",
    "author_key" : "priyadarshinim_contus",
    "timespent" : NumberLong(18000),
    "comment" : "Added charts in the dashboard page of the application.",
    "created_on" : "2017-08-16T18:22:04.816+0530",
    "updated_on" : "2017-08-16T18:22:04.816+0530",
    "started_on" : "2017-08-16T18:21:39.000+0530",
    "started_date" : "2017-08-02",
    "updated_date" : "2017-08-02",
    "role" : "PHP",
    "updated_at" : ISODate("2017-09-29T15:27:48.069Z"),
    "created_at" : ISODate("2017-09-29T15:27:48.069Z"),
    "status" : 1.0
}

I need to get record with help of started date , by default I will give two date in that i will check $gt and $lt of started date .

        $current_date =  '2017-08-31';
        $sixmonthfromcurrent ='2017-08-01';

     $worklogs = Worklog::raw ( function ($collection) use ($issue_jira_id, $current_date, $sixmonthfromcurrent) {
     return $collection->aggregate ( [ 
              ['$match' => ['issue_id' => ['$in' => $issue_jira_id],
                          'started_date' => ['$lte' => $current_date,'$gte' => $sixmonthfromcurrent] 
                    ] 
              ],

              ['$group' => ['issue_id' => ['$push' => '$issue_id'],
                          '_id' => ['year' => ['$year' => '$started_date'],
                          'week' => ['$week' => '$started_date'],'resource_key' => '$author_key'],
                          'sum' => array ('$sum' => '$timespent')] 
              ],
              [ '$sort' => ['_id' => 1] 
              ] 
        ] );
     } );

if i run this query am getting this type of error can't convert from BSON type string to Date ,how to rectify this error, Thanks in advance..



via Chebli Mohamed

jeudi 5 octobre 2017

How to keep $errors variable from being set as empty array

I have a fairly large site which I've recently moved to another server where it's been duplicated among a handful of VMs which all sit behind a load balancer. Since then, I've been spotting these errors in the logs.

Fatal error: Call to a member function has() on array (View: /var/www/sites/lotpro/public_html/resources/views/home.blade.php)

The offending line looks like the following:

<div class="form-group margin-sm ">

Keeping in mind this is Laravel 5.1, which is when everything is still stored in a singular routes.php file rather than split between web.php and api.php, I found this to be very strange, I shouldn't have to worry about giving my routes the correct middleware as it's already applied globally. The docs for 5.1 clearly state the $errors variable will always be available and will be an instance of MessageBag. In this case though, I was able to determine it's an empty array.

There are also similar occurrences in other files where I am also checking the $errors variable so I believe there isn't anything wrong with the code itself as I am unable to reproduce the issue.

I determined there may be an issue with the file session driver in regards to having the site behind a load balancer and running on multiple VMs so I spun up a shared Redis server and now I have the site using the redis session driver and it seems to have largely cleared up the issue. Unfortunately it does still very intermittently exist.

Each time we call a method on the $errors object, I could first check to see if it is an object, but that feels more like sweeping the issue under the rug and not actually fixing the underlying issue of not having a functioning session.



via Chebli Mohamed

CSS not updating on change laravel

i'm currently working on a project in laravel 5.1 and i can't figure out what i'm doing wrong.

I use gulp to update my scss files to css files. Everytime i run gulp my files get updates the way they should be updated, but my browser doesn't find the updates.

In my editor the .css file is correct, but my browser doesn't register the updates.

cntrl + shift + f5 doens't work either. Anbody has a solution for me?



via Chebli Mohamed

notfoundhttp exception while post request

I have researched all the previous answers of this similar question, yet I couldnt found any.

I am simply accessing the function which I have made custom

Routes

Route::post('dashboard', 'Admin\UserController@index');

UserController.php

<?php
namespace App\Http\Controllers;

use DB;
use Session;
use App\Http\Requests;
use Illuminate\Http\Request;

class UserController extends Controller 
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        echo "welcome"

    }
}

When I am trying this,it throws me

NotFoundHttpException in RouteCollection.php line 161:

error.



via Chebli Mohamed

Laravel 5.1 Basic Authentication

I am newbie to laravel, I have several doubts here to ask. It's like when I do basic login and registeration using Auth Class which is by default provided by Laravel 5.1, it gives me 404 Not found error.

Here is my directory structure:

resources/views/auth/register.blade.php
resources/views/auth/login.blade.php

I am following laravel 5.1 official doc, to get this. When I press for submit button in register form it throws me 404 not found error.

register.blade.php

<!-- resources/views/auth/register.blade.php -->

<form method="POST" action="/auth/register">
    {!! csrf_field() !!}

    <div>
        Name
        <input type="text" name="name" value="">
    </div>

    <div>
        Email
        <input type="email" name="email" value="">
    </div>

    <div>
        Password
        <input type="password" name="password">
    </div>

    <div>
        Confirm Password
        <input type="password" name="password_confirmation">
    </div>

    <div>
        <button type="submit">Register</button>
    </div>
</form>

I have my auth class as a :

app/Http/Controllers/Auth/AuthController.php
app/Http/Controllers/Auth/PasswordController.php

My basic routes:

// Authentication routes...
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');

// Registration routes...
Route::get('auth/register', 'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');


Route::controllers([
   'password' => 'Auth\PasswordController',
]);

Still it throws me 404 not found error. Any Solution What I am missing? Also the routes shows AuthController@getRegister, do I have to manually create the function of getRegister, as I couldn't find any.? I am new to laravel

Also my AuthController.php looks like

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    protected $redirectPath = '/dashboard';
    protected $loginPath = '/login';
    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}



via Chebli Mohamed

mercredi 4 octobre 2017

check or condition in where clause

I want to check OR condition for the variable role_id in role_mapping table. I want to check if user_id has role_id either '2' or '3'. User with user_id=210 has role_id 2 and 1. but my query result prints '3'. How to use or condition in Laravel query?

Role table
  user_id role_id 
   210     2
   210     1

    $user_role=role_mapping::where('user_id','=',210)
    ->where('role_id','=','2')
    ->orwhere('role_id','=','3')
    ->select('role_mapping.role_id')->first();

     echo $user_role->role_id;  // print 3



via Chebli Mohamed

mardi 3 octobre 2017

Laravel: Count number of rows in a relashionship

I have the following relationship:

  • A venue has many offers
  • A offer has many orders

I have the following Eloquent model to represent this:

class Venue {
    public function orders()
    {
        return $this->hasManyThrough(Order::class, Offer::class);
    }
}

I want to determine the total number of orders for venues with location_id = 5 using Laravel's Eloquent model.

The only way I managed to do this is as follows:

$venues = Venue::where('location_id', 5)->with('orders')->get();

$numberOfOrders = 0;
foreach($venues as $venue) {
    $numberOfOrders += $venue->orders->count();
}
dump($numberOfOrders); // Output a single number (e.g. 512)

However, this is obviously not very efficient as I am calculating the count using PHP instead of SQL.

How can I do this using Eloquent model alone.



via Chebli Mohamed

lundi 2 octobre 2017

Add recaptcha to default Laravel Password Reset

I want to require the users of my Laravel 5.1 application to have finished a Google Recaptcha process, but I can't figure out how to safely modify the code that sends the reset password link.

The code that does this for me is the "postEmail()" function in the inherited trait "ResetsPassword". This is my entire PasswordController:

use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Foundation\Auth\ResetsPasswords;

class PasswordController extends Controller {

use ResetsPasswords;

/**
 * Create a new password controller instance.
 *
 * @param  \Illuminate\Contracts\Auth\Guard  $auth
 * @param  \Illuminate\Contracts\Auth\PasswordBroker  $passwords
 * @return void
 */
public function __construct(Guard $auth, PasswordBroker $passwords)
{
    $this->auth = $auth;
    $this->passwords = $passwords;

    $this->middleware('guest');
}

}

As you can see, all the real methods are in the "ResetsPasswords" trait which is in a vendor file so I don't want to modify it directly. How do I modify the "postEmail()" function in the inherited trait safely in my PasswordsController?



via Chebli Mohamed