dimanche 11 septembre 2016

nested categories routing in Laravel 5.1

I have catalog with 4 nested categoies levels. Each subcategory could have items and/or nested categories. As long as I walking on the subcategory pages everything is OK. But when I try to go to item page, then I get ModelNotFoundException, because Laravel cannot understand that it is not category anymore.

-Catalog     (instance of Category model level 1)
--Cat1       (instance of Category model level 2)
--Product1   (instance of Item model)
--Product2
--Product3
...
--Cat2       (instance of Category model level 2)
---Product1  (instance of Item model)
---Product2
---Product3
...
---Cat3      (instance of Category model level 3)
----Product1 (instance of Item model)
----Product2
----Product3
...
----Cat3      (instance of Category model level 4)
-----Product1 (instance of Item model)
-----Product2
-----Product3

routes.php

    Route::get('catalog', ['as' => 'catalog.index', 'uses' => 'CatalogController@getIndex']);
    Route::get('catalog/{category}', ['as' => 'catalog.cat', 'uses' => 'CatalogController@getCategory'])->where(['category' => '.*']);
    // {category} could be equal to 'doors' or 'doors/glass' or unfinite number of sublevels
    Route::get('catalog/{category}/{item}', ['as' => 'catalog.item', 'uses' => 'CatalogController@getItem']);
    // this route is never working, because laravel always render {category}/{item} as {category} 

RouteServiceProvider.php

public function boot(Router $router)
{
    parent::boot($router);

    Route::bind('category', function($cat) {
        $bread = explode("/", substr($cat, 0));
        $sef = array_pop($bread);
        return Category::whereSef($sef)->firstOrFail();
    });


}

Every category in database has sef which is not equal to path
Example: url = http://ift.tt/2cmQx0j
Sef for glass = glass (not catalog/doors/glass)
That is why I use explode in RouteServiceProvider to catch sef of element after last slash.

The problem is when I have url for the item then I have following error

ModelNotFoundException in Builder.php line 223: No query results for model [App\Category].

This happens because in URL http://ift.tt/2c7ZEov laravel still looking door1 in Category model not in Item model. But I don't know what to do to explain laravel that $category is finished now.



via Chebli Mohamed

samedi 10 septembre 2016

How to remove public word from laravel URL

Currently I am using Shared Web Hosting, and uploaded my Laravel project (developed in Laravel 5.1), but I have to type to public with domain name. eg: http://ift.tt/2cf4grG

My Hosting seller not mapping my domain to laravel public folder so Its mapped to public_html folder.

Is there any way available to remove public word from URL? I tried to keep my files in public_html folder and moved public folder out of `public_html' folder, but no luck,

Kindly guideme



via Chebli Mohamed

vendredi 9 septembre 2016

Laravel 5.1 send email (Connection could not be established with host smtp.gmail.com [connection time out #110]

I'm learning Laravel 5.1 mail for my project. So, I try to send simple email first from a new Laravel 5.1 application on my localhost.

this is my .env config file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=mygmail@gmail.com
MAIL_PASSWORD=mygmailpassword
MAIL_ENCRYPTION=tls

and this is my config/mail.php

'driver' => env('MAIL_DRIVER', 'smtp'),

'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

'port' => env('MAIL_PORT', 587),

'from' => ['address' => 'sender@gmail.com', 'name' => 'Sender'],

'encryption' => env('MAIL_ENCRYPTION', 'tls'),

'username' => env('MAIL_USERNAME'),

'password' => env('MAIL_PASSWORD'),

'sendmail' => '/usr/sbin/sendmail -bs',

this is my function to send the email

Mail::send('emails.email', ['user'=>'Sender'], function($m){

    $m->to('receiver@yahoo.com','receiver')->subject('subject');
});

With this, when I run the application, it always return the error

Swift_TransportException in StreamBuffer.php line 265:

Connection could not be established with host smtp.gmail.com [Connection timed out #110]

What I've tried:

  • Turn on 'less secure apps' on google account
  • 2-step verification (generate an app password) and use it on (MAIL_PASSWORD on .env config)

But, none of this succeed. What am I doing wrong here?

PS: My OS is Linux Ubuntu 14.04



via Chebli Mohamed

Duplicate records in User's Session Maangement

For the User Session Management, I set the SESSION_DRIVER=database and in database there is session table.

Schema::create('tblsession', function ($table) {
    $table->string('id')->unique();
    $table->integer('user_id')->nullable();
    $table->string('ip_address', 45)->nullable();
    $table->text('user_agent')->nullable();
    $table->text('payload');
    $table->integer('last_activity');
});

Here issue is: whenever i login, it keep creating the new User's Session records. I am using same Chrome browser and same Tab.

Did I miss anything in doing the configuration? I am following Session Management as described here



via Chebli Mohamed

Updated Laravel 5.2 - No Auth

I developed a application in Laravel 5.1 and i needed make a laravel update to 5.2.

Now that i finished, i can not make a Auth, every time return false.

App.php

 'providers' => [

    /*
     * Laravel Framework Service Providers...
     */
    Illuminate\Foundation\Providers\ArtisanServiceProvider::class,
    Illuminate\Auth\AuthServiceProvider::class,
    // Sarav\Multiauth\MultiauthServiceProvider::class,
    Illuminate\Broadcasting\BroadcastServiceProvider::class,
    Illuminate\Bus\BusServiceProvider::class,
    Illuminate\Cache\CacheServiceProvider::class,
    Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
    // Illuminate\Routing\ControllerServiceProvider::class,
    Illuminate\Cookie\CookieServiceProvider::class,
    Illuminate\Database\DatabaseServiceProvider::class,
    Illuminate\Encryption\EncryptionServiceProvider::class,
    Illuminate\Filesystem\FilesystemServiceProvider::class,
    Illuminate\Foundation\Providers\FoundationServiceProvider::class,
    // Illuminate\Hashing\HashServiceProvider::class,
    App\Providers\ShaHashServiceProvider::class,
    Illuminate\Mail\MailServiceProvider::class,
    Illuminate\Pagination\PaginationServiceProvider::class,
    Illuminate\Pipeline\PipelineServiceProvider::class,
    Illuminate\Queue\QueueServiceProvider::class,
    Illuminate\Redis\RedisServiceProvider::class,
    Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
    Illuminate\Session\SessionServiceProvider::class,
    Illuminate\Translation\TranslationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\View\ViewServiceProvider::class,

    Collective\Html\HtmlServiceProvider::class,

    // Captcha
    Mews\Captcha\CaptchaServiceProvider::class,

    /*
     * Application Service Providers...
     */
    App\Providers\AppServiceProvider::class,
    App\Providers\AuthServiceProvider::class,
    App\Providers\EventServiceProvider::class,
    App\Providers\RouteServiceProvider::class,
    App\Providers\ViewServiceProvider::class,

],

/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/

'aliases' => [

    'App'       => Illuminate\Support\Facades\App::class,
    'Artisan'   => Illuminate\Support\Facades\Artisan::class,
    'Auth'      => Illuminate\Support\Facades\Auth::class,
    'Blade'     => Illuminate\Support\Facades\Blade::class,
    'Bus'       => Illuminate\Support\Facades\Bus::class,
    'Cache'     => Illuminate\Support\Facades\Cache::class,
    'Config'    => Illuminate\Support\Facades\Config::class,
    'Cookie'    => Illuminate\Support\Facades\Cookie::class,
    'Crypt'     => Illuminate\Support\Facades\Crypt::class,
    'DB'        => Illuminate\Support\Facades\DB::class,
    'Eloquent'  => Illuminate\Database\Eloquent\Model::class,
    'Event'     => Illuminate\Support\Facades\Event::class,
    'File'      => Illuminate\Support\Facades\File::class,
    'Gate'      => Illuminate\Support\Facades\Gate::class,
    'Hash'      => Illuminate\Support\Facades\Hash::class,
    'Input'     => Illuminate\Support\Facades\Input::class,
    'Inspiring' => Illuminate\Foundation\Inspiring::class,
    'Lang'      => Illuminate\Support\Facades\Lang::class,
    'Log'       => Illuminate\Support\Facades\Log::class,
    'Mail'      => Illuminate\Support\Facades\Mail::class,
    'Password'  => Illuminate\Support\Facades\Password::class,
    'Queue'     => Illuminate\Support\Facades\Queue::class,
    'Redirect'  => Illuminate\Support\Facades\Redirect::class,
    'Redis'     => Illuminate\Support\Facades\Redis::class,
    'Request'   => Illuminate\Support\Facades\Request::class,
    'Response'  => Illuminate\Support\Facades\Response::class,
    'Route'     => Illuminate\Support\Facades\Route::class,
    'Schema'    => Illuminate\Support\Facades\Schema::class,
    'Session'   => Illuminate\Support\Facades\Session::class,
    'Storage'   => Illuminate\Support\Facades\Storage::class,
    'URL'       => Illuminate\Support\Facades\URL::class,
    'Validator' => Illuminate\Support\Facades\Validator::class,
    'View'      => Illuminate\Support\Facades\View::class,
    'Form'      => Collective\Html\FormFacade::class,
    'Html'      => Collective\Html\HtmlFacade::class,
    'Captcha'   => Mews\Captcha\Facades\Captcha::class

],

routes.php

Route::group(['middleware' => ['web']], function () {
    Route::get('/', function(){

        dd( Auth::attempt(['email' => 'campos@company.com.br', 'senha' => '1234567890' ] ) );

    });
});

Auth.php

return [

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' =>  App\Clientes::class,
        ],
        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],
];

Aditional info: My laravel not has the default de hash (bcrypt), i'm using Shahash.

(When i used the Laravel 5.1, all work fine ... Before Upgrade to 5.2 the Auth not working....)

I create a new customer to test register and login. The password has encrypt with shahash, all ok. But on Auth never return True



via Chebli Mohamed

Dompdf is not working in laravel 5.1's console/kernel.php

Css float is not working while running the function inside Kernel.php

But it works properly in normal controller function.

This is kernel.php

    $schedule->call(function () {

        $poolMail = EmailPool::where('status', 0)->get();
        foreach($poolMail as $p)
        {
        $this->createReservationPdf($content['rcode']);
        }

    })->everyMinute();



    public function createReservationPdf($resId)
{
    $rsvData = \App\Reservation::where('reservation_code', $resId)->first();
    $rsvPayment = \App\ReservationPayment::where('reservation_code', $resId)->first();
    $rsvExtras = \App\RsvExtra::where('r_no', $resId)->get();
    $rsvInsurances = \App\RsvInsurance::where('r_no', $resId)->get();

    $pStation = \App\Station::where('istasyon_kodu', $rsvPayment->pstation)->first();
    $rStation = \App\Station::where('istasyon_kodu', $rsvPayment->rstation)->first();
    $carGroup = \App\Group::where('grp', $rsvPayment->vgroup)->first();


    $pdf = \PDF::loadView('pdf.test', compact('rsvData', 'rsvPayment', 'rsvExtras', 'rsvInsurances', 'pStation', 'rStation', 'carGroup'));
    return $pdf->save(storage_path().'/'.$resId.'.pdf');
}

And createReservationPdf is working well in any other controller.

Actually, it was working until a couple of days ago.



via Chebli Mohamed

Laravel 5.1 Session expires after a few requests

I'm using Laravel 5.1 with Jessengers for my web application. I have explored this issue many times over here, on Github and Laracasts but still stuck in solving this. I'm using SESSION_DRIVER=file in my environment file, also tried increasing 'lifetime' => 120, to let's say 1200, however, I know that's in minutes but that was a try. My session doesn't even last for one minute. Here's my session.php file.

    return [

    /*
    |--------------------------------------------------------------------------
    | Default Session Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the default session "driver" that will be used on
    | requests. By default, we will use the lightweight native driver but
    | you may specify any of the other wonderful drivers provided here.
    |
    | Supported: "file", "cookie", "database", "apc",
    |            "memcached", "redis", "array"
    |
    */

    'driver' => env('SESSION_DRIVER', 'file'),

    /*
    |--------------------------------------------------------------------------
    | Session Lifetime
    |--------------------------------------------------------------------------
    |
    | Here you may specify the number of minutes that you wish the session
    | to be allowed to remain idle before it expires. If you want them
    | to immediately expire on the browser closing, set that option.
    |
    */

    'lifetime' => 120,

    'expire_on_close' => false,

    /*
    |--------------------------------------------------------------------------
    | Session Encryption
    |--------------------------------------------------------------------------
    |
    | This option allows you to easily specify that all of your session data
    | should be encrypted before it is stored. All encryption will be run
    | automatically by Laravel and you can use the Session like normal.
    |
    */

    'encrypt' => false,

    /*
    |--------------------------------------------------------------------------
    | Session File Location
    |--------------------------------------------------------------------------
    |
    | When using the native session driver, we need a location where session
    | files may be stored. A default has been set for you but a different
    | location may be specified. This is only needed for file sessions.
    |
    */

    'files' => storage_path('framework/sessions'),

    /*
    |--------------------------------------------------------------------------
    | Session Database Connection
    |--------------------------------------------------------------------------
    |
    | When using the "database" or "redis" session drivers, you may specify a
    | connection that should be used to manage these sessions. This should
    | correspond to a connection in your database configuration options.
    |
    */

    'connection' => null,

    /*
    |--------------------------------------------------------------------------
    | Session Database Table
    |--------------------------------------------------------------------------
    |
    | When using the "database" session driver, you may specify the table we
    | should use to manage the sessions. Of course, a sensible default is
    | provided for you; however, you are free to change this as needed.
    |
    */

    'table' => 'sessions',

    /*
    |--------------------------------------------------------------------------
    | Session Sweeping Lottery
    |--------------------------------------------------------------------------
    |
    | Some session drivers must manually sweep their storage location to get
    | rid of old sessions from storage. Here are the chances that it will
    | happen on a given request. By default, the odds are 2 out of 100.
    |
    */

    'lottery' => [0, 100],

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Name
    |--------------------------------------------------------------------------
    |
    | Here you may change the name of the cookie used to identify a session
    | instance by ID. The name specified here will get used every time a
    | new session cookie is created by the framework for every driver.
    |
    */

    'cookie' => 'laravel_session',

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Path
    |--------------------------------------------------------------------------
    |
    | The session cookie path determines the path for which the cookie will
    | be regarded as available. Typically, this will be the root path of
    | your application but you are free to change this when necessary.
    |
    */

    'path' => '/',

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Domain
    |--------------------------------------------------------------------------
    |
    | Here you may change the domain of the cookie used to identify a session
    | in your application. This will determine which domains the cookie is
    | available to in your application. A sensible default has been set.
    |
    */

    'domain' => null,

    /*
    |--------------------------------------------------------------------------
    | HTTPS Only Cookies
    |--------------------------------------------------------------------------
    |
    | By setting this option to true, session cookies will only be sent back
    | to the server if the browser has a HTTPS connection. This will keep
    | the cookie from being sent to you if it can not be done securely.
    |
    */

    'secure' => false,

];



via Chebli Mohamed