mercredi 31 août 2016

Quality must range from 0 to 100 - Intervention Laravel 5.x

I'm using intervention/image 2.3. When I try to upload an image I got the following error :

InvalidArgumentException in AbstractEncoder.php line 212

Quality must range from 0 to 100

Below is my code for that :

$file = Input::file('image');
$filename = time() . '.' . $file->getClientOriginalExtension();
Image::make($file)->resize(50, 50)->save(storage_path() . DIRECTORY_SEPARATOR . 'uploads', $filename);

Any single guidance will help me alot.



via Chebli Mohamed

How can I get the thumbnail/image and desciption of a foreign url, like facebook or twitter?

I want to create an application where users can share link from other websites and a thumbnail/image appear with a little description under it (something like facebook, twitter, reddit..), how can I get to recognize whether the user actually posted a link and automatically generate a thumbnail and an description from that website if it has one

I'm trying to do this with laravel!



via Chebli Mohamed

Laravel 5.2 swiftmailer library `_swiftmailer_init` function is not loading

I'm working in laravel 5.2 on PHP version 5.6.25. I'm getting issue with swiftmailer library to send emails. I'm getting this error when sending email on my live server

InvalidArgumentException in Response.php line 458: 
The HTTP status code "0" is not valid.

When I searched online regarding this issue. Then got solution for this to add one line vendor/swiftmailer/swiftmailer/lib/swift_required.php file.

require dirname(__FILE__).'/swift_init.php';

But this line is already added in this file. But inside a function which is loading using autoloading. Below is the code of this file

if (class_exists('Swift', false)) {
    return;
}

// Load Swift utility class
require dirname(__FILE__).'/classes/Swift.php';

if (!function_exists('_swiftmailer_init')) {
    function _swiftmailer_init()
    {
        require dirname(__FILE__).'/swift_init.php';
    }
}

// Start the autoloader and lazy-load the init script to set up dependency injection
Swift::registerAutoload('_swiftmailer_init');

It seems that last line Swift::registerAutoload('_swiftmailer_init'); is not working.

This issue is getting on live server.. But working properly on my local server and testing server also. My local server has '5.5.9' php version. Please help me on this.

Thanks in Advance.



via Chebli Mohamed

migrate command on laravel 5.1 console

I have created many tables use migration file, but i have dropped some table via the mysql command line tool, then i find the migration status about the tables i have dropped is still ran, so how can i fix it?

when i use migrate command, it always says nothing to migrate, but i have no ta ble in my database.

I have tried delete all the logs and stuff under the storage path, i have also tried to delete the migration table on mysql or change .env file to use a new database, but both can not works, anyone can help me?

I use laravel 5.1.



via Chebli Mohamed

multi auth not working in laravel 5.1

I am using Laravel 5.1 and I need multiple login in my project so I am trying Kbwebs\MultiAuth and Sarav\Multiauth for multi auth, both are worked with user model model but unfortunately when I use TenderApplicant model Auth::attempt return false every times.

I searched all over and trying to figure out the problem

This is my code

app.php

'providers' => [

    /*
     * Laravel Framework Service Providers...
     */
    Illuminate\Foundation\Providers\ArtisanServiceProvider::class,
    Illuminate\Auth\AuthServiceProvider::class,
    Sarav\Multiauth\MultiauthServiceProvider::class,
    ...

auth.php

return [
'multi' => [
    'admin' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
        'table' => 'sa_users',
    ],
    'user' => [
        'driver' => 'eloquent',
        'model'  => App\Models\TenderApplicant::class,
        'table'  => 'tender_applicant',
    ],
],
'password' => [
    'email'  => 'emails.password',
    'table'  => 'sa_password_resets',
    'expire' => 60,
],

];

AuthController.php

class AuthController extends Controller
{

use AuthenticatesAndRegistersUsers, ThrottlesLogins;

public function __construct()
{
    $this->middleware('guest', ['except' => 'getLogout']);
}

public function userAuth(Request $request)
{
    $this->validate($request, ['email' => 'required','password' => 'required']);

    $email      = $request->input('email');
    $password   = $request->input('password');
    var_dump(Auth::attempt("user", ['email' => 'awal.ashu@gmail.com', 'password' => '123456']));
}

return false for user but admin worked perfected.

TenderApplicant.php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class TenderApplicant extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table      = 'tender_applicant';
    protected $primaryKey = 'TE_APP_ID';
    const CREATED_AT      = 'CREATED_AT';
    const UPDATED_AT      = 'UPDATED_AT';

    protected $fillable = [
                        'TENDER_ID', 
                        'SCHEDULE_ID', 
                        'PR_DETAIL_ID', 
                        'NID', 
                        'PR_CATEGORY', 
                        'PR_TYPE', 
                        'APPLICANT_NAME',
                        'EMAIL',  
                        'APPLICANT_PHONE', 
                        'PASSWORD', 
                        'HOLDING_NO', 
                        'IS_TE_SC_BOUGHT', 
                        'TE_SC_AMOUNT', 
                        'TE_SC_DATE', 
                        'SPOUSE_NAME', 
                        'BID_AMOUNT',
                        'BG_AMOUNT', 
                        'BG_AMOUNT_TEXT',
                        'BANK_ID',
                        'B_DRAFT_NO', 
                        'B_DRAFT_DATE', 
                        'B_DRAFT_ATTACHMENT', 
                        'IS_SELECTED', 
                        'IS_ACTIVE', 
                        'CREATED_BY', 
                        'UPDATED_BY'
                    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = ['TE_APP_ID'];

    /**
     * Password need to be all time encrypted.
     *
     * @param string $password
     */
    public function setPasswordAttribute($password)
    {
        $this->attributes['PASSWORD'] = bcrypt($password);
    }
}



via Chebli Mohamed

Use php variables in Laravel to send mail

I mates,I have this code in my Controller:

             $name      =   Input::get('fname')." " .Input::get('lname');
             $message   =   Input::get('message');
             $email     =   Input::get('email');
             $subject   =   Input::get('subject');
             $phone     =   Input::get('phone');
             $area      =   \App\Area::find(1)->name;
             $ticket    =   \App\Area::find(1)->ticket_sent;
             Mail::send('help.send', [ 'Mmessage' => $message, 'Mname' => $name, 'Memail' => $email, 'Msubject' => $subject, 'Mphone' =>$phone, 'Marea' => $area, 'Mticket' => $ticket], function ($message)
             {

                $message->from('asd@gmail.com', 'Name');*

                $message->to('support@mycompany.it');

                $message->subject('Support');

             });
             $macroArea = MacroArea::find(1);
             $macroArea->ticket_sent =$ticket+1;
             $macroArea->save();
            Session::flash('message', 'The message was successfully send. We will get back to you within 2 business days!');
            return Redirect::to('helpDesk');

It works so good, but I'm trying to change two rows in:

                $message->from($email, $name);

                $message->subject($subject);

But it doesn't work. What am I doing wrong? I don't understand.



via Chebli Mohamed

Superfeedr response not working in laravel

I want to retrieve feeds from superfeedr.com using PubSubHubbub api, but my callback response is not working. Here is my code

class Superfeedr
{
    private $topic;
    private $callback;
    private $hub = 'http://ift.tt/H95U5N';
    public $verbose = false;

    function __construct($topic, $callback, $hub='')
    {
        $this->topic = $topic;
        $this->callback = $callback;
        if ($hub) {
            $this->hub = $hub;
        }
    }

    public function request($mode)
    {

        $post_data = array ( 
            'hub.mode'  => 'retrieve',
            'hub.callback'  => urlencode($this->callback),
            'hub.topic' => urlencode($this->topic)
        ); 


        foreach ($post_data as $key=>$value) { 
            $post_data_string .= $key.'='. $value.'&'; 
        } 


        $url =$this->hub .'?'.$post_data_string;

        $ch = curl_init(); 

        curl_setopt($ch, CURLOPT_URL, $url); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
        curl_setopt($ch, CURLOPT_USERPWD, 'testdata:1234');
        curl_setopt($ch, CURLOPT_BUFFERSIZE, 4096);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 25);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $output = curl_exec($ch);
    }   
}

and my php file is

  #Retrieve.php

  $superfeedr = new Superfeedr('http://ift.tt/1mxyvpX', 
                        'http://ift.tt/2bQUWgt', 
                        'http://ift.tt/KSzPYJ');

  $superfeedr->verbose = true;
  $data = $superfeedr->request('list');

Here I want to inform you that my callback url is one of my laravel action. Which is

public function callback(Request $request)
{
    \Log::info("Testing before callback");
    if(isset($_Get["hub_challenge"])){
       echo $_Get["hub_challenge"];
       return;
    }

    // Just for testing
    \DB::table('test')->insert(['name' => "Test callback data. Please ignore"]);

}

But nothing happens in my log file and database too. Somebody have any idea then please let me know whats wrong here. Thanks.



via Chebli Mohamed

mardi 30 août 2016

class Memcached not found in laravel 5.1

Laravel 5.1 is reporting class memcached not found, i have looked in almost all related threads but cant seem to find exactly answer. I'm using WAMP server on Windows.



via Chebli Mohamed

404 Error when Testing Request class validation through Chrome Postman Extension

Below is my Controller Action method. You can see I passed a param of Request Class to validate before going to save the data in database

public function store(RoleRequest $request)
{
}

My Request class is below.

class RoleRequest extends Request
{
    private $Role;

    public function __construct(IRole $_role) {
        $this->Role = $_role;
    }        
    public function authorize()
    {
        return true;
    }    
    public function rules()
    {
        return [
            'Role' => 'required|max:20|min:4,
        ];
    }    
}

Above code works perfectly when I run it through web page(blade).

I created one more controller for API to Send save request. Below is the code

class RoleApiController extends Controller
{
    public function store(RoleRequest $request)
    {

    }
}

Issue comes, when I type just 1 char for role name and the Request class impose validation and I get 404 error This time I am sending request from Postman Extension in Chrome.



via Chebli Mohamed

Method filter does not exist when updating from Laravel 5.1 to 5.2

I am trying to update from Laravel 5.1 to 5.2. composer update ran succesfully. Here is my composer.json:

{
  "name": "laravel/laravel",
  "description": "The Laravel Framework.",
  "keywords": [
    "framework",
    "laravel"
  ],
  "license": "MIT",
  "type": "project",
  "require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.2.*",
    "aws/aws-sdk-php-laravel": "~3.0",
    "vinkla/hashids": "^2.2",
    "cartalyst/sentinel": "~2.0.1",
    "baum/baum": "~1.1",
    "robclancy/presenter": "1.3.*",
    "barryvdh/laravel-ide-helper": "^2.0",
    "league/flysystem-aws-s3-v3": "~1.0",
    "intervention/image": "^2.2",
    "rap2hpoutre/laravel-log-viewer": "^0.2.8",
    "league/fractal": "^0.12.0",
    "ramsey/uuid": "~2.8",
    "lucadegasperi/oauth2-server-laravel": "~5.1",
    "torann/geoip": "0.2.*@dev",
    "mailchimp/mailchimp": "^2.0",
    "iron-io/iron_mq": "~2.0",
    "aws/aws-sdk-php": "~3.0",
    "justinrainbow/json-schema": "~1.3",
    "sybio/gif-frame-extractor": "^1.0",
    "coldume/imagecraft": "dev-gif-optimization",
    "pragmarx/firewall": "^0.5.2",
    "get-stream/stream-laravel": "dev-master",
    "roumen/sitemap": "2.5.*",
    "guzzlehttp/guzzle": "~6.0",
    "bugsnag/bugsnag-laravel": "1.*",
    "cviebrock/image-validator": "^2.0",
    "toin0u/geocoder-laravel": "@stable",
    "embedly/embedly-php": "0.5.*",
    "facebook/webdriver": "^1.0",
    "scotteh/php-dom-wrapper": "dev-composer-symfony-fix",
    "scotteh/php-goose": "dev-composer-guzzle-fix",
    "doctrine/dbal": "^2.5",
    "mandrill/mandrill": "1.0.*"
  },
  "repositories": [
    {
      "type": "vcs",
      "url": "http://ift.tt/2aYTVR8"
    },
    {
      "type": "vcs",
      "url": "http://ift.tt/2aWXGDe"
    },
    {
      "type": "vcs",
      "url": "http://ift.tt/2aYU07z"
    }
  ],
  "require-dev": {
    "symfony/dom-crawler": "~3.0",
    "symfony/css-selector": "~3.0",
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~4.0",
    "phpspec/phpspec": "~2.1",
    "laracasts/testdummy": "~2.0"
  },
  "autoload": {
    "classmap": [
      "database"
    ],
    "psr-4": {
      "Garagesocial\\": "app/"
    }
  },
  "autoload-dev": {
    "classmap": [
      "tests"
    ]
  },
  "scripts": {
    "post-install-cmd": [
      "php artisan clear-compiled",
      "php artisan optimize"
    ],
    "pre-update-cmd": [
      "php artisan clear-compiled"
    ],
    "post-update-cmd": [
      "php artisan clear-compiled",
      "php artisan ide-helper:generate",
      "php artisan optimize"
    ],
    "post-root-package-install": [
      "php -r \"copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
      "php artisan key:generate"
    ]
  },
  "config": {
    "preferred-install": "dist",
    "github-oauth": {
      "github.com": "e0530adb37eea46a185bdfc096bc709d842471fe"
    }
  }
}

However, when it launches php artisan clear-compiled the following error appears:

[BadMethodCallException]
Method filter does not exist.

Without any further information. As I understand, filter was deprecated, but I do not use filters in my routes.php. If I try to load any page, here is the exception I am getting:

    BadMethodCallException in Macroable.php line 74:
    Method filter does not exist.


    in Macroable.php line 74
    at Router->__call('filter', array('fw-block-bl', '\PragmaRX\Firewall\Filters\Blacklist')) in ServiceProvider.php line 163
    at Router->filter('fw-block-bl', '\PragmaRX\Firewall\Filters\Blacklist') in ServiceProvider.php line 163
    at ServiceProvider->registerFilters() in ServiceProvider.php line 67
    at ServiceProvider->register() in Application.php line 554
    at Application->register(object(ServiceProvider)) in ProviderRepository.php line 74
    at ProviderRepository->load(array('Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', 'Illuminate\Broadcasting\BroadcastServiceProvider', 'Illuminate\Bus\BusServiceProvider', 'Illuminate\Cache\CacheServiceProvider', 'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider', 'Illuminate\Cookie\CookieServiceProvider', 'Illuminate\Database\DatabaseServiceProvider', 'Illuminate\Encryption\EncryptionServiceProvider', 'Illuminate\Filesystem\FilesystemServiceProvider', 'Illuminate\Foundation\Providers\FoundationServiceProvider', 'Illuminate\Hashing\HashServiceProvider', 'Illuminate\Mail\MailServiceProvider', 'Illuminate\Pagination\PaginationServiceProvider', 'Illuminate\Pipeline\PipelineServiceProvider', 'Illuminate\Queue\QueueServiceProvider', 'Illuminate\Redis\RedisServiceProvider', 'Illuminate\Auth\Passwords\PasswordResetServiceProvider', 'Illuminate\Session\SessionServiceProvider', 'Illuminate\Translation\TranslationServiceProvider', 'Illuminate\Validation\ValidationServiceProvider', 'Illuminate\View\ViewServiceProvider', 'Garagesocial\Providers\AppServiceProvider', 'Garagesocial\Providers\BusServiceProvider', 'Garagesocial\Providers\ConfigServiceProvider', 'Garagesocial\Providers\EventServiceProvider', 'Garagesocial\Providers\RouteServiceProvider', 'Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider', 'Vinkla\Hashids\HashidsServiceProvider', 'Cartalyst\Sentinel\Laravel\SentinelServiceProvider', 'Baum\Providers\BaumServiceProvider', 'Robbo\Presenter\PresenterServiceProvider', 'Aws\Laravel\AwsServiceProvider', 'Intervention\Image\ImageServiceProvider', 'Rap2hpoutre\LaravelLogViewer\LaravelLogViewerServiceProvider', 'Torann\GeoIP\GeoIPServiceProvider', 'LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider', 'LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider', 'Roumen\Sitemap\SitemapServiceProvider', 'GetStream\StreamLaravel\StreamLaravelServiceProvider', 'Bugsnag\BugsnagLaravel\BugsnagLaravelServiceProvider', 'Cviebrock\ImageValidator\ImageValidatorServiceProvider', 'Toin0u\Geocoder\GeocoderServiceProvider', 'PragmaRX\Firewall\Vendor\Laravel\ServiceProvider', 'Garagesocial\Providers\MailerServiceProvider', 'Garagesocial\Providers\ValidationServiceProvider', 'Garagesocial\Providers\Headers\HeadersModelServiceProvider', 'Garagesocial\Providers\Factories\GenappFactoryServiceProvider', 'Garagesocial\Providers\Factories\ObjectFactoryServiceProvider', 'Garagesocial\Providers\Factories\HeaderFactoryServiceProvider', 'Garagesocial\Providers\Factories\TransformerFactoryServiceProvider')) in Application.php line 530
    at Application->registerConfiguredProviders() in RegisterProviders.php line 17
    at RegisterProviders->bootstrap(object(Application)) in Application.php line 203
    at Application->bootstrapWith(array('Illuminate\Foundation\Bootstrap\DetectEnvironment', 'Illuminate\Foundation\Bootstrap\LoadConfiguration', 'Illuminate\Foundation\Bootstrap\ConfigureLogging', 'Illuminate\Foundation\Bootstrap\HandleExceptions', 'Illuminate\Foundation\Bootstrap\RegisterFacades', 'Illuminate\Foundation\Bootstrap\RegisterProviders', 'Illuminate\Foundation\Bootstrap\BootProviders')) in Kernel.php line 232
    at Kernel->bootstrap() in Kernel.php line 127
    at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
    at Kernel->handle(object(Request)) in index.php line 65

Could you please help me to get rid of this error? All the stack trace references the internal files which I do not want to edit manually, and I am not sure how to fix that



via Chebli Mohamed

Failure to update Laravel 5.1 to 5.2 (these conflict with your requirements or minimum-stability)

Couple weeks ago I asked this question about trying to upgrade from Laravel 5.1 to 5.2 - Updating Larael from 5.1.35 to 5.2.* - fails to upgrade symfony/css-selector

Although I was given very nice and clear answer, that did not help. As instructed, I have updated "lucadegasperi/oauth2-server-laravel" to "~5.1", but I still have the same error.

My composer.json

  {
  "name": "laravel/laravel",
  "description": "The Laravel Framework.",
  "keywords": [
    "framework",
    "laravel"
  ],
  "license": "MIT",
  "type": "project",
  "require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.2.*",
    "aws/aws-sdk-php-laravel": "~3.0",
    "vinkla/hashids": "^1.1",
    "cartalyst/sentinel": "~2.0.1",
    "baum/baum": "~1.1",
    "robclancy/presenter": "1.3.*",
    "barryvdh/laravel-ide-helper": "^2.0",
    "league/flysystem-aws-s3-v3": "~1.0",
    "intervention/image": "^2.2",
    "rap2hpoutre/laravel-log-viewer": "^0.2.8",
    "league/fractal": "^0.12.0",
    "ramsey/uuid": "~2.8",
    "lucadegasperi/oauth2-server-laravel": "~5.1",
    "torann/geoip": "0.2.*@dev",
    "mailchimp/mailchimp": "^2.0",
    "iron-io/iron_mq": "~2.0",
    "aws/aws-sdk-php": "~3.0",
    "justinrainbow/json-schema": "~1.3",
    "sybio/gif-frame-extractor": "^1.0",
    "coldume/imagecraft": "dev-gif-optimization",
    "pragmarx/firewall": "^0.5.2",
    "get-stream/stream-laravel": "dev-master",
    "roumen/sitemap": "2.5.*",
    "guzzlehttp/guzzle": "~6.0",
    "bugsnag/bugsnag-laravel": "1.*",
    "cviebrock/image-validator": "^2.0",
    "toin0u/geocoder-laravel": "@stable",
    "badawy/embedly": "^1.0",
    "facebook/webdriver": "^1.0",
    "scotteh/php-dom-wrapper": "dev-composer-symfony-fix",
    "scotteh/php-goose": "dev-composer-guzzle-fix",
    "doctrine/dbal": "^2.5",
    "mandrill/mandrill": "1.0.*"
  },
  "repositories": [
    {
      "type": "vcs",
      "url": "http://ift.tt/2aYTVR8"
    },
    {
      "type": "vcs",
      "url": "http://ift.tt/2aWXGDe"
    },
    {
      "type": "vcs",
      "url": "http://ift.tt/2aYU07z"
    }
  ],
  "require-dev": {
    "symfony/dom-crawler": "~3.0",
    "symfony/css-selector": "~3.0",
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~4.0",
    "phpspec/phpspec": "~2.1",
    "laracasts/testdummy": "~2.0"
  },
  "autoload": {
    "classmap": [
      "database"
    ],
    "psr-4": {
      "*********************": "****"
    }
  },
  "autoload-dev": {
    "classmap": [
      "tests"
    ]
  },
  "scripts": {
    "post-install-cmd": [
      "php artisan clear-compiled",
      "php artisan optimize"
    ],
    "pre-update-cmd": [
      "php artisan clear-compiled"
    ],
    "post-update-cmd": [
      "php artisan clear-compiled",
      "php artisan ide-helper:generate",
      "php artisan optimize"
    ],
    "post-root-package-install": [
      "php -r \"copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
      "php artisan key:generate"
    ]
  },
  "config": {
    "preferred-install": "dist",
    "github-oauth": {
      "github.com": "**************************************"
    }
  }
}

The full text of error:

>> composer update
php artisan clear-compiled
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
    - laravel/framework v5.1.43 requires symfony/css-selector 2.7.* -> satisfiable by symfony/css-selector[2.7.x-dev, v2.7.0, v2.7.0-BETA1, v2.7.0-BETA2, v2.7.1, v2.7.10, v2.7.11, v2.7.12, v2.7.13, v2.7.14, v2.7.15, v2.7.16, v2.7.2, v2.7.3, v2.7.4, v2.7.5, v2.7.6, v2.7.7, v2.7.8, v2.7.9] but these conflict with your requirements or minimum-stability.
    - Conclusion: don't install laravel/framework v5.2.45
    - Conclusion: don't install laravel/framework v5.2.44
    - Conclusion: don't install laravel/framework v5.2.43
    - Conclusion: don't install laravel/framework v5.2.42
    - Conclusion: don't install laravel/framework 5.2.41
    - Conclusion: don't install laravel/framework v5.2.40
    - Conclusion: don't install laravel/framework v5.2.39
    - Conclusion: don't install laravel/framework v5.2.38
    - Conclusion: don't install laravel/framework v5.2.37
    - Conclusion: don't install laravel/framework v5.2.36
    - Conclusion: don't install laravel/framework v5.2.35
    - Conclusion: don't install laravel/framework v5.2.34
    - Conclusion: don't install laravel/framework v5.2.33
    - Conclusion: don't install laravel/framework v5.2.32
    - Conclusion: don't install laravel/framework v5.2.31
    - Conclusion: don't install laravel/framework v5.2.30
    - Conclusion: don't install laravel/framework v5.2.29
    - Conclusion: don't install laravel/framework v5.2.28
    - Conclusion: don't install laravel/framework v5.2.27
    - Conclusion: don't install laravel/framework v5.2.26
    - Conclusion: don't install laravel/framework v5.2.25
    - Conclusion: don't install laravel/framework v5.2.24
    - Conclusion: don't install laravel/framework v5.2.23
    - Conclusion: don't install laravel/framework v5.2.22
    - Conclusion: don't install laravel/framework v5.2.21
    - Conclusion: don't install laravel/framework v5.2.20
    - Conclusion: don't install laravel/framework v5.2.19
    - Conclusion: don't install laravel/framework v5.2.18
    - Conclusion: don't install laravel/framework v5.2.17
    - Conclusion: don't install laravel/framework v5.2.16
    - Conclusion: don't install laravel/framework v5.2.15
    - Conclusion: don't install laravel/framework v5.2.14
    - Conclusion: don't install laravel/framework v5.2.13
    - Conclusion: don't install laravel/framework v5.2.12
    - Conclusion: don't install laravel/framework v5.2.11
    - Conclusion: don't install laravel/framework v5.2.10
    - Conclusion: don't install laravel/framework v5.2.9
    - Conclusion: don't install laravel/framework v5.2.8
    - Conclusion: don't install laravel/framework v5.2.7
    - Conclusion: don't install laravel/framework v5.2.6
    - Conclusion: don't install laravel/framework v5.2.5
    - Conclusion: don't install laravel/framework v5.2.4
    - Conclusion: don't install laravel/framework v5.2.3
    - Conclusion: don't install laravel/framework v5.2.2
    - Conclusion: don't install laravel/framework v5.2.1
    - vinkla/hashids 1.1.0 requires illuminate/support 5.0.*|5.1.* -> satisfiable by laravel/framework[v5.1.43], illuminate/support[v5.0.0, v5.0.22, v5.0.25, v5.0.26, v5.0.28, v5.0.33, v5.0.4, v5.1.1, v5.1.13, v5.1.16, v5.1.2, v5.1.20, v5.1.22, v5.1.25, v5.1.28, v5.1.30, v5.1.31, v5.1.41, v5.1.6, v5.1.8].
    - vinkla/hashids 1.1.0 requires illuminate/support 5.0.*|5.1.* -> satisfiable by laravel/framework[v5.1.43], illuminate/support[v5.0.0, v5.0.22, v5.0.25, v5.0.26, v5.0.28, v5.0.33, v5.0.4, v5.1.1, v5.1.13, v5.1.16, v5.1.2, v5.1.20, v5.1.22, v5.1.25, v5.1.28, v5.1.30, v5.1.31, v5.1.41, v5.1.6, v5.1.8].
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.1
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.13
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.16
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.2
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.20
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.22
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.25
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.28
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.30
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.31
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.41
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.6
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.1.8
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.0.22
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.0.25
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.0.26
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.0.28
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.0.33
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.0.0
    - don't install laravel/framework v5.2.0|don't install illuminate/support v5.0.4
    - Installation request for laravel/framework 5.2.* -> satisfiable by laravel/framework[5.2.41, v5.2.0, v5.2.1, v5.2.10, v5.2.11, v5.2.12, v5.2.13, v5.2.14, v5.2.15, v5.2.16, v5.2.17, v5.2.18, v5.2.19, v5.2.2, v5.2.20, v5.2.21, v5.2.22, v5.2.23, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.29, v5.2.3, v5.2.30, v5.2.31, v5.2.32, v5.2.33, v5.2.34, v5.2.35, v5.2.36, v5.2.37, v5.2.38, v5.2.39, v5.2.4, v5.2.40, v5.2.42, v5.2.43, v5.2.44, v5.2.45, v5.2.5, v5.2.6, v5.2.7, v5.2.8, v5.2.9].
    - Installation request for vinkla/hashids ^1.1 -> satisfiable by vinkla/hashids[1.1.0].



via Chebli Mohamed

Live Chat with Laravel, Redis and Socket.IO

I am trying to create a real time live chat with Laravel 5.1 (I am using AsgardCMS), Redis and Socket.IO. My logic is when a guest user opens the chat window to fire an event to a specific operator user. To do so I am broadcasting the event to a channel (channel-name)+(operator id), because I want to show a notification to a specific operator, who is logged in the backend of the website. What I find difficult is how to get the id of the operator in the server side code for Redis, which is listening for events. This is the code:

var server = require('http').Server();

var io = require('socket.io')(server);

var Redis = require('ioredis');
var redis = new Redis();

redis.subscribe('asgardcms.notifications.3');

redis.on('message', function(channel, message) {
    console.log(channel, message);
    message = JSON.parse(message);

    io.emit(channel + ':' + message.event, message.data);

});

io.sockets.on('connection', function (socket){
    // console.log(socket);
});

server.listen(3000);

Here I have hardcoded 3 in the name of the channel but I want this value to change so I can notify a certain operator.



via Chebli Mohamed

Queuing multi-tenant application in Laravel

I have a multi-tenant application built in Laravel 5.1. It uses one main database connection for storing users, roles, permissions, as well as jobs and failed_jobs. Additionally, every user has his own database.

I use a Job class for sending mail, and when it is executed, the following exception occurs:

[PDOException] SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected

The class uses tables from two db connections (the main connection, and the one associated with the current user).

Thanks in advance, any help is appreciated.



via Chebli Mohamed

lundi 29 août 2016

What is the best practice to delete all relationships in Laravel?

I need to delete all relationships of product. I got error when I trying to delete item with relationships. Here is my code:

public function getDelete(Product $product)
{
    $name = $product->name;

    $product->Field()->Data()->delete();
    $product->Field()->delete();
    $product->delete();

    return redirect('products')->with('success', 'Product <b>'.$name.'</b> successfully deleted.');
}

Here is models:

public function Field()
{
    return $this->hasMany("\App\ProductField", 'product_id','id');
}

public function Data()
{
    return $this->hasMany("\App\ProductFieldData", 'product_field_id','id');
}

BadMethodCallException in Builder.php line 2101: Call to undefined method Illuminate\Database\Query\Builder::Data()

This error I got If product don't have a ProductFieldData. But I think its must be skipped if don't have relationships data?

How to delete product all relationships?



via Chebli Mohamed

Laravel 5.1 returns null text values as string "null"

I'm using Laravel 5.1 and have a Eloquent query that gets values from a mysql database, and when the textfields are NULL in the database, they come back as "null" in the json. I would like them to come back as null (not a string, just null). Is there an easy way to do this for any (or all) values in the database, or do I have to write an accessor for every field I want this applied to?

Just to reiterate/demonstrate, the json currently comes back as this:

{
  id : 1,
  first : "jason",
  last  : "null"
}

And I'd like it to be like this instead

{
  id : 1,
  first : "jason",
  last  : null
}

The mysql field last is declared as varchar, allow null, default null.



via Chebli Mohamed

Laravel 5.1 Passing data (controller -> view)

I'm new to Laravel, I want to understand what is the best approach to share values from controllers to views: I have found few ways of doing it :

  1. view()->share('variable_name',$value);
  2. session(['variable_name'=>$value]);
  3. return view('viewname')->with('variable_name'=>$value);

Is there any difference between these ways? Also, is it a good practice to share data from the model(from design point of view)?

Thanks



via Chebli Mohamed

cURL csv file submission returning OK status but no data is uploaded

I'm having difficulty uploading a .csv file through a cURL request to a RESTful API. I'm receiving a successful response (200 OK) but no data appears to be submitted:

{
  "meta": [
  ],
  "code": 200,
  "object": "csvfile",
  "data": [
  ],
  "time": 1472464675
}

This is being made with the following request. I've added commenting to break down each of the CURL_SETOPTS:

    // create a CURLFile object
    $cfile = curl_file_create($fileName,'text/csv', $fileName);

    // start curl request
    $curl = curl_init();

    // assign POST data
    $data = array('file' => $cfile);

    // specify POST request
    curl_setopt($curl, CURLOPT_POST, true);

    // basic auth
    curl_setopt($curl, CURLOPT_USERPWD, getenv('USERNAME').':'.getenv('PASSWORD'));

    // destination URI
    curl_setopt($curl, CURLOPT_URL, 'http://ift.tt/2c2bzlv');

    // associate curlfile
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    // since we're using PHP 5.6 we need to enable CURLOPT_SAFE_UPLOAD
    curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);

    // return options
    curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($curl, CURLOPT_VERBOSE, true);
    curl_setopt($curl, CURLOPT_STDERR, $out);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    // debugging
    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        echo("CURL RESPONSE: ");
        echo $response;
    }
    curl_close($curl);

I should mention I don't fully understand the importance of the $postname field in CURLfile objects. Furthermore I'm not entirely sure what I'm doing by assign POST data as demonstrated in the construct's documentation (http://ift.tt/1YZS8eC).

Note: I'm writing this in a Laravel application and am aware of the Guzzle client but have opted to present the problem this way, as there's more support for typical cURL problems on SO. I believe the issue is something to do with my cURLfile creation but have spent hours trying to pinpoint it.

What could be causing this issue?



via Chebli Mohamed

dimanche 28 août 2016

make table with foreach and for work in same time

here I would like to make a table where there number of rows will automatically be made in accordance with the data in $ kosts-> stock_room. and then there is also I want to make the data directly arranged with the data I have on the table residents by room number, so if i have data in table 'residents' with room number 10 its will fill the table with row 10.

here my code :

<table class="table table-hover table-striped">
        <tr>
            <th width="10%">Action</th>
            <th>Room</th>
            <th>Kost</th>
            <th>Name</th>
            <th>Due Date</th>
        </tr>        
        <tr>
            @foreach($posts as $row)
            @for($i=1;$i<=$kosts->stock_room;$i++) 
            <tr>
            <td>                
            <a title='Edit Data' class='btn btn-xs btn-warning' href=''><i class='fa fa-pencil'></i></a>
            <a title='Delete Data' class='btn btn-xs btn-danger' href='' onclick="return confirm('sure to delete ?')"><i class='fa fa-trash'></i></a>                      
            </td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            </tr>   
            @endfor
            @endforeach
        </tr>
    </table>

have someone can help me, to make my code can work exactly like I want?

and iam sorry for my bad english



via Chebli Mohamed

how can i use relationship in laravel?

My schema is as follows:

channel table:
id int unsigned primary key auto increment,
name varchar(30) not null,
...

category table:
id int unsigned primary key auto increment,
channel_id int unsigned index,
name varchar(30) not null,
...

article table:
id int unsigned primary key auto increment,
category_id int unsigned index,
title varchar(90) not null,
content text not null,
...

so, every article belong to a specific category and the category belongs to a specific channel.

my question is:

how can i search all the articles with the category name and channel name (the relationship is ready in my code)?

i have tried

$articles = App\Article::latest()->with('category')->with('channel')->get();

but it does not work, anyone who can help me? thank you for your time.



via Chebli Mohamed

Laravel 5.1 - Paypal error

i have a problem with complete payment with paypal, i have this error:

Got Http response code 400 when accessing http://ift.tt/1f12BzJ.

MY CONTROLLER

$payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $items = array();
        $subtotal = 0;
        $cart = \Session::get('cart'); // Get info by my session cart
        $currency = 'EUR';

        // i extract info by session cart and count the Subtotal 

        foreach($cart as $producto){
            $item = new Item();
            $item->setName($producto->name)
            ->setCurrency($currency)
            ->setDescription($producto->extract)
            ->setQuantity($producto->quantity)
            ->setPrice($producto->price);

            $items[] = $item;
            $subtotal += $producto->quantity * $producto->price;
        }

        // i calculated my $price_coupon and here i want make the discount.
        // price coupon can be ZERO or >0

        $subtotal_coupon = $subtotal - $price_coupon  ;

        $item_list = new ItemList();
        $item_list->setItems($items);
        // set up subtotal (with discount coupon) 
        $details = new Details();
        $details->setSubtotal($subtotal_coupon)
        ->setShipping($get_session->shipping);

        // here i calculated the total amount for paypal payment
        // i extracted the price of shipping from my DB, so $get_session->shipping work well

        $total = $subtotal_coupon + $get_session->shipping;

        $amount = new Amount();
        $amount->setCurrency($currency)
            ->setTotal($total)
            ->setDetails($details);

Important! if i don't add my coupon, it work well! like this:

    $payer = new Payer();
    $payer->setPaymentMethod('paypal');

    $items = array();
    $subtotal = 0;
    $cart = \Session::get('cart'); //get session cart
    $currency = 'EUR';

    // extract info by session cart
    foreach($cart as $producto){
        $item = new Item();
        $item->setName($producto->name)
        ->setCurrency($currency)
        ->setDescription($producto->extract)
        ->setQuantity($producto->quantity)
        ->setPrice($producto->price);

        $items[] = $item;
        $subtotal += $producto->quantity * $producto->price;
    }

    // items
    $item_list = new ItemList();
    $item_list->setItems($items);

    $details = new Details();
    $details->setSubtotal($subtotal)
    ->setShipping($get_session->shipping);

    $total = $subtotal + $get_session->shipping;

    $amount = new Amount();
    $amount->setCurrency($currency)
        ->setTotal($total)
        ->setDetails($details);

I don't know why when i add the calculation of discount COUPON, it give me a error.

Thank you for your help guys!



via Chebli Mohamed

Query with pivot table laravel 5.1

Query with pivot table laravel

Mappings

enter image description here

I am having a trouble with pivot query.

App/Entities/user.php

public function roles()
{
    return $this->belongsToMany('App\Entities\UserRole', 'user_user_roles', 'user_id', 'user_role_id');
}


public function getPivotCondition($roleId)
{
    return $this->roles()->wherePivot('user_role_id',$roleId);
}

Controller

    public function getUserWithRole(){

    $users = $User->getPivotCondition(1)->get();

    dd($users);

    }        

It results in a query

    SELECT `user_roles`.*, 
       `user_user_roles`.`user_id`      AS `pivot_user_id`, 
       `user_user_roles`.`user_role_id` AS `pivot_user_role_id` 
FROM   `user_roles` 
       INNER JOIN `user_user_roles` 
               ON `user_roles`.`id` = `user_user_roles`.`user_role_id` 
WHERE  `user_user_roles`.`user_id` IS NULL 
       AND `user_user_roles`.`user_role_id` = '1' 

my question is that why i am getting user_user_roles.user_id is null in my query

I know that i can use WhereHas but i am looking for an alternative.



via Chebli Mohamed

Sort multidimensional array by another array and complete missing keys in the same order

I'm trying to export data from leads table to excel using PHP/Laravel, the leads table caמ be customized to show specific columns and the export columns should be same as the table columns. the problem is - if column not exists in a specific row the column not shown empty and the 'xls' file is exported really messy... my code looks like this:

public function excelExport(Request $request, $client_id=null)
{

    $client_id = is_null($client_id) ? \Auth::client()->id : $client_id;

    if(is_null($this->client_users)){
        $this->client_users = $this->clientsController->listClientUsers($client_id);
    }

    $columns = $this->account_settings->getColumnsDef($client_id);
    $query = Lead::select(array_keys($columns))->where('client_id',strval($client_id))->where('deleted',0);
    $query = $this->setQueryDates($request,$query,$client_id);
    $query = $this->leadsFiltersController->setExportQuery($request,$query);
    $arr = $query->get()->toArray();

    Excel::create('leads' , function($excel) use ($arr,$columns){

        $excel->sheet('Leads' , function($sheet) use ($arr,$columns){

            $rows = [];
            $count = 0;

            foreach($arr as $lead){
                $row = $this->setExportRowData($lead,$count,$columns);
                $rows[] = $row;
                $count++;
            }
            $sheet->fromArray($rows);

        });

    })->export('xls');


 private function setExportRowData($lead,$count,$columns,$order = true)
{
    $row = [];
    $order = null;
    foreach($lead as $k => $v) {
if (is_array($v)) {

            switch (strtolower($k)) {

                case "ga_details":
                    if (count($v) > 2) {
                        foreach ($v as $key => $ga_detail) {
                            if ($key != "realTime_data" && $key != "uacid") {
                                $row[$key] = $ga_detail;
                            }
                        }
                    }
                    break;

                case "status":
                    if (isset($v['name']) && count($v['name'])) {
                        $row['status'] = $v['name'];
                    } else {
                        $row['status'] = "no status";
                    }
                    break;

                case "owner":
                    if (isset($v['owner_id']) && count($v)) {
                        $row['owner'] = $this->getClientOwnerUserName($this->client_users, $v['owner_id']);
                    } else {
                        $row['owner'] = "no owner";
                    }
                    break;

                case "prediction":
                    if (isset($v['score']) && count($v)) {
                        $row['prediction'] = $v['score'];
                    } else {
                        $row['prediction'] = "no prediction";
                    }
                    break;

                case "the_lead":
                    foreach ($v as $key => $lead_detail) {
                        $row[$key] = $lead_detail;
                    }
                    break;
                case "quality":
                    if (isset($v['name'])) {
                        $row['quality'] = $v['name'];
                    } else {
                        $row['quality'] = "no quality";
                    }
                    break;

                case "feeds":
                    if (isset($v['feeds']) && count($v['feeds'])) {
                        $row['feeds'] = array_pop($v['feeds'])['message'];
                    }
                    break;

                default :
                    $row[$k] = $v;
                    break;

            }

        } else {
            if ($k != "_id") {
                $row[$k] = $v;
            }

        }


    }

    return $order == true ? sortArrayByArrayValues($this->order,$row) : $row;
}

sortArrayByArrayValues function looks like this:

function sortArrayByArrayValues(Array $array, Array $orderArray)
{
    $rtn = [];
    foreach($array as $arr){
        if(isset($orderArray[$arr])){
            $rtn[$arr] = $orderArray[$arr];
        }else{
            $rtn[$arr] = '';
        }
    }
    return $rtn;
}

I really have no clue how to solve it, appreciate any help!!! :)



via Chebli Mohamed

How can I get sessions created earlier in laravel

I need to sort my sessions by created earlier in Laravel, And I don't use session table. To do this you have any suggestions? I don't know by filename or any ? thanks all and sorry for my terrible English grammer.



via Chebli Mohamed

samedi 27 août 2016

Return result after the event is fired in Laravel 5.2

My original code is below

/*
   Create the Role
*/  

$result = (new RoleDb())->Create($obj);

if($result["Success"]) {

    /*
    | Get all Modules 
    */

    $Permissions = $this->Module->All($obj->RoleID);
    $list = [];

    /*
    | Prepare the list that will be assigned to Newly created role.
    */

    foreach($Permissions["Data"] as $Permission) {
        $RolePermissionOM = new RolePermissionOM();
        $RolePermissionOM->PermissionID             = $Permission->PermissionID;
        $RolePermissionOM->IsActive                 = $Permission->DefaultPermission;
        $RolePermissionOM->RoleID                   = $result["Data"];
        array_push($list, $RolePermissionOM);
    }

    /*
    | Create default permissions for above created role.
    */

    return $this->RolePermission->CreateDefaultPermissions($list, $result["Data"]);
}

Now, in my application, there are 3 more points where role is being created and instead of code duplication, I though to convert this code into event. SO whenever a role is being created, an Event is being fired to create the permission records for that role.I wrote the below code.

Event::fire(new RoleCreationEvent($result));
// `$result` contains the newly created RoleID.

Question : In my original code, I was able to get the result to check if the permissions are saved correctly or not. How will I do that in case of firing the Event ?



via Chebli Mohamed

vendredi 26 août 2016

Laravel 5.1 404 not found on apache server

i have currently hosted laravel 5.1 application to my 1and1.com server and i am facing a 404 not found errors to all my routes except for the root route i.e http://ift.tt/2brNlzO

the root route is working with get request but all the other routes are coming as 404 not found , everything is working good in localhost.

My application folder structure:

  • -example.com

  • -server

    • App
    • database
    • config
    • storage
    • .env
    • .htaccess
    • index.php
    • server.php

as you can see that i have removed the default laravel public folder and moved the contents to root.

My .htaccess

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]   RewriteCond     %{REQUEST_URI} !^  RewriteRule ^(.*)$ /$1 [L]  </IfModule>

My Index.php

<?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylorotwell@gmail.com>
 */

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels nice to relax.
|
*/

require __DIR__.'/bootstrap/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);

Server.php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylorotwell@gmail.com>
 */
$uri = urldecode(
    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);

// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
if ($uri !== '/' && file_exists(__DIR__.''.$uri)) {
    return false;
}

require_once __DIR__.'index.php';

Routes.php

Route::get('/', function(){
        echo'test';exit();
    });//test

Route::get('/s', function(){
        echo'testss';exit();
    });//test   

now if you see that the first route is working fine , but when i do http://ift.tt/2boi1VQ this gives 404 not found. i hope my question is clear to all , thanks.



via Chebli Mohamed

MethodNotAllowedHttpException RouteCollection.php line 218

I try to pass a value by post to post.... I take the select value and send it at create file, after this the user compile other form and send it to other route post and check the validation... But don't work ->Route.php

Route::get('administrator/','AdministratorController@index');
Route::get('administrator/select','AdministratorController@select');
Route::post('administrator/create','AdministratorController@create');
Route::post('administrator','AdministratorController@store');

->AdministratorController

    public function create(Request $request){

    $chapterS=SubChapters::where('ChapterName',$request->chapters)->get();
    return view('administrator_pages.create',compact('chapterS','request'));
   }

        public function store(Request $request){
        //dd($request->all());
            $this->validate($request,['IdQuestion'=>'required']);
            return 'store';
        }

->administrator_pages.create

@extends('app')

@section('content')




<div class="input-group">
        <span class="input-group-addon" id="basic-addon1">Capitolo Scelto:</span>
        {!! Form::text('Chapter',$request->chapters,['class'=>'form-control','readonly'=>'readonly']) !!}
</div>

<br>

<div class="input-group">
    <span class="input-group-addon" id="basic-addon1">Sotto Capitolo: </span>

        <div class="dropdown">


          <select name="SubChapterID"class="btn btn-default dropdown-toggle">
            @foreach($chapterS as $chapter)
                <option value=""></option>
            @endforeach

            </select>

        </div>

</div><!--//SUBCHAPTERID-->
<br>

<div class="input-group">
    <span class="input-group-addon" id="basic-addon1">Id Domanda :</span>

    {!! Form::text('IdQuestion',null,['class'=>'form-control']) !!}
</div><!-- ID QUESTION -->
    <br>
<div class="input-group">
    <span class="input-group-addon" id="basic-addon1">Immagine: </span>

    {!! Form::text('UrlImg',null,['class'=>'form-control']) !!}
</div><!-- URL IMG-->
    <br>
<div class="input-group">
    <span class="input-group-addon" id="basic-addon1">Domanda:</span>

    {!! Form::textarea('Contenent',null,['class'=>'form-control','rows'=>'5']) !!}
</div><!-- Contenet -->
    <br>



        <div class="input-group">

            <span class="input-group-addon" id="basic-addon1">Risposta:</span>
            <!-- <div class="form-control">&nbsp;-->&nbsp; &nbsp;
{!!            Form::radio('Answer', 'Vero') !!} Vero     &nbsp; &nbsp;
{!!            Form::radio('Answer', 'Falso') !!} Falso

</div>

<!-- </div>-->



    <br>
<div class="input-group">
    <span class="input-group-addon" id="basic-addon1">Spiegazione:</span>

    {!! Form::textarea('Explanation',null,['class'=>'form-control','rows'=>'5']) !!}
</div><!-- Explanation-->
    <br>

    {!! Form::submit('Avanti',['class'=>'btn btn-default']) !!}

@if($errors->any())

    <ul class="alert alert-danger">
        @foreach($errors->all() as $error)
            <li></li>
        @endforeach
    </ul>

@endif



@stop

->Error

 1/1 MethodNotAllowedHttpException in RouteCollection.php line 218:

    in RouteCollection.php line 218
    at RouteCollection->methodNotAllowed(array('POST')) in RouteCollection.php line 205
    at RouteCollection->getRouteForMethods(object(Request), array('POST')) in RouteCollection.php line 158
    at RouteCollection->match(object(Request)) in Router.php line 821
    at Router->findRoute(object(Request)) in Router.php line 691
    at Router->dispatchToRoute(object(Request)) in Router.php line 675
    at Router->dispatch(object(Request)) in Kernel.php line 246
    at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
    at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
    at CheckForMaintenanceMode->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
    at Pipeline->Illuminate\Routing\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
    at Pipeline->then(object(Closure)) in Kernel.php line 132
    at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
    at Kernel->handle(object(Request)) in index.php line 54



via Chebli Mohamed

Hashing passwords on client side before sending to server in laravel 5.1

Greeting of the evening :)

I am working on an application on https where user fill login form and submit then one array send to server but security auditor said hacker can see password in plain text to give check as control. I tried but application gone down. there is any way solve it?



via Chebli Mohamed

Display list and details using separate controllers in Laravel

I'm using the following two routes in my app, but they are failing. (only one works when I switch the positions). Notice that I'm using two separate controllers. What's the correct way of specifying routes for a scenario like this?

Route::controller('schedulers', 'SchedulersController', [
    'getIndex' => 'schedulers.index',
    'getUpdate' => 'schedulers.edit'
]);


Route::controller('schedulers/{schedulerId}', 'ReportsController', [
    'getIndex' => 'schedulers.reports',
]);



via Chebli Mohamed

Laravel 5.1 and Typeahead.js

I am attempting to use typeahed.js in my Laravel 5.1 blade view. I trying to recreate The Basics typeahed example but the states aren't displaying when attempting to search them.

Here is the code My main layout

<html>
<head>
    <title>App Name - @yield('title')</title>
    ">--}}
    <script src="http://ift.tt/1XwG72U"></script>
    <script type="text/javascript" src=""></script>


    


    <script type="text/javascript" src=""></script>

    <link href="" rel="stylesheet">
    <link href="" rel="stylesheet">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

    <script src="http://ift.tt/1CveVTY"></script>





</head>
<body>
@section('sidebar')

@show

<div class="container">
    @yield('content')
</div>
</body>
</html>

My blade view I am trying to view it in

@extends('layouts.main')



@section('content')

    <div id="the-basics">
        <input class="typeahead" type="text" placeholder="States of USA">
    </div>
@endsection

@section('scripts')
    <script src="http://ift.tt/1LZ42nF"></script>
    <script src="http://ift.tt/1CveVTY"></script>
    <script>
        var substringMatcher = function(strs) {
            return function findMatches(q, cb) {
                var matches, substringRegex;

                // an array that will be populated with substring matches
                matches = [];

                // regex used to determine if a string contains the substring `q`
                substrRegex = new RegExp(q, 'i');

                // iterate through the pool of strings and for any string that
                // contains the substring `q`, add it to the `matches` array
                $.each(strs, function(i, str) {
                    if (substrRegex.test(str)) {
                        matches.push(str);
                    }
                });

                cb(matches);
            };
        };

        var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
                      'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
                      'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
                      'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
                      'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
                      'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
                      'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
                      'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
                      'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
        ];

        $('#the-basics .typeahead').typeahead({
                                                  hint: true,
                                                  highlight: true,
                                                  minLength: 1
                                              },
                                              {
                                                  name: 'states',
                                                  source: substringMatcher(states)
                                              });
    </script>

@stop


via Chebli Mohamed

Laravel REST API backend to connect with html/css/js frontend mobile

I would like to develop a mobile app using laravel. I research it and it is possible if you make REST API. Assuming that I already created my laravel rest api backend, how can I connect it with my frontend?. Should I still use the blade template by laravel or do I need to create a separate folder containing my frontend not include in the laravel app?. I'm confuse on how to do it because most of the tutorials are using angular and ionic for the frontend which I'm not very skilled yet and I'm trying to avoid using them because it's difficult for me. For now I just want to focus on using html/css/js. And also if I can use phonegap for this thing.



via Chebli Mohamed

Sending email in Laravel with form and with multiple addresses

my focus is to send an email with a form where you can insert: name, last name, from(any email), to (my email). First of all I have tried using the google configuration(see on internet), but the email don't send, the result is a blank page. I must configuration only services.php and .env ?



via Chebli Mohamed

Laravel Blade does not include css and .js present in template

I need, from a view-blade, to search a database in order to fetch data and display them in another view-blade when a link is clicked.

I made the following:

In the view-blade who will acting on database:

@foreach($pending as $p)
 <tr>
   <td>
     <a href="">Click here</a>
   </td>
 </tr>
@endforeach

the connected 'route' is

Route::get("/getMyForm/{ident}", ['as' => "openMyPage", 'uses' => "BusinessController@seeMyForm"]); 

the method on BusinessController has

public function seeMyForm($ident){
$myResult=DB::select(...);
return view('MyViewBlade')->with('myResult', $myResult);
}

the master template (PrincipalView.blade.php) (as was included in the view-blade to display

<!DOCTYPE html>
<html>

    <head>
        <meta name="csrf_token" content="" />



    <meta name="viewport" content="width=device-width, initial-scale=1.0">  

    <link href="assets/css/bootstrap.min.css" rel="stylesheet">  
    <link href="assets/css/bootstrap-theme.min.css" rel="stylesheet">  

    <link href="assets/css/bootstrap-datepicker.min.css" rel="stylesheet">              
    <!-- <link rel="stylesheet" href="assets/js/jquery-ui/jquery-ui.css"> -->
    <script src="assets/js/jquery.js"></script>  

    <!-- <script type="text/javascript" src="http://ift.tt/1JDUibz"></script> -->

    <script src="assets/js/bootstrap-datepicker.js"></script>      
    <script src="assets/js/bootstrap.min.js"></script>

    <link href="http://ift.tt/2aDsFEU" rel="stylesheet"> 
    <script src="http://ift.tt/2aDrLs2"></script> 

    <script src="assets/js/jquery-ui-1.11.4.custom/jquery-ui.js"></script>
    <link rel="stylesheet" href="assets/js/jquery-ui-1.11.4.custom/jquery-ui.css">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="assets/js/jquery-pessoal.js"></script> 
    <script src="assets/js/jquery-pessoal2.js"></script> 

    <link rel="stylesheet" href="assets/plugins/multiple-select-master/multiple-select.css"></script>       
    <script src="assets/plugins/multiple-select-master/multiple-select.js"></script> 

    <link href="assets/css/custom.css" rel="stylesheet"> 

</head>
...
    <div class="container">


        @yield("corpo")


    </div>
...

the view-blade which will display (ToAproveView.blade.php)

@extends('PrincipalView')
@section('corpo')
<div class="row">
  <div class="col-sm-6">
    <div class="form-group">
     <label>Cliente Principal: </label><br>
        <input type="text" id="idTxtFaturamentoAprovacaoCliente" 
name="namTxtFaturamentoAprovacaoCliente" 
readonly  value=""/>

    </div>  
</div>

is not working. The last view-blade do not render its elements. The view opens itself not well formatted.

Other actions make all other views-blade ok.

I found out, the problem is connected with the line code

 <a href="">Click here</a>

because it was created on the fly (I guess).

Looking at the console of Chrome, is there

GET http://ift.tt/2bUSjX1 
29638_1472048778961_121:16 GET http://ift.tt/2bD0RnE 
29638_1472048778961_121:18 GET http://ift.tt/2bURmhs 
29638_1472048778961_121:13 GET http://ift.tt/2bD2dio 
29638_1472048778961_121:22 GET http://ift.tt/2bUTSUK 
 29638_1472048778961_121:28 GET http://ift.tt/2bD2stK 
net::ERR_CONNECTION_RESET
29638_1472048778961_121:29 GET http://ift.tt/2bURpdg 
net::ERR_CONNECTION_RESET
29638_1472048778961_121:23 GET http://ift.tt/2bD2x0x 
net::ERR_CONNECTION_RESET

The including css and js files do not work (the names in the path are different of that I was wrote abore because I made a translation to better comprehension)



via Chebli Mohamed

Where to put things in Laravel 5.1

I'm a bit confused about where something like this belongs to Laravel.

I want to write a web service client wrapper in laravel, and I want to access it like this:

\MyWSClient::getSomeInfoAbout($someId);

then the code will connect to the web service to http://ift.tt/2bFLpsC$someid&type=json with OAuth2 or some token requests, then fetch the data, keep token information until it expires, refresh token if needed etc.

But where will I put the code? In the vendor directory as a new package? I'm moving this code from a computer to another computer except vendor,storage and node_modules folders, because they are huge and when I do this, I will have to move only one folder in the vendor directory. And I'll need to publish a package under development to composer if I want portability etc.

Is there any other way to do something like this?



via Chebli Mohamed

Laravel named routes array

Named routes, the best thing that's created by Laravel. But is it's possible in some way to add an array of named routes which can be used?

I did the follow:

Route::get('/', [
    'as' => ['url', 'secondurl'],
    'uses' => 'ViewController@index'
]);

but it returned an eror, Illegal offset type.

Is this simply not possible or did I do something wrong?



via Chebli Mohamed

Laravel: passing data with Mail:queue() to a view

I'm passing some data to email view. But when I execute Mail::queue() ,It shows following error in terminal when I check with

php artisan queue:listen.

Following error showing in terminal

Argument 1 passed to Illuminate\Queue\Jobs\Job::resolveAndFire() must be of the type array, integer given, called in /home/aamir/project1/vendor/laravel/framework/src/Illuminate/Queue/Jobs/DatabaseJob.php on line 50 and defined

Controller Code

$feedbacklink = url() . '/survey/' . $randomstring;
$email_data = array(
                    'name' => "$getbuyername",
                    'email' => "$getbuyeremail",
                    'inspector' => "$inspectorname",
                    'files' => $list,
                    'link' => $feedbacklink,
                    'para1' => "$para1",
                    'address' => "$reportaddress"
                    );
Mail::queue('emails.frontendreportfeedback', $email_data, function($message) use ($email_data) {
           $message->from('abc@gmail.com', 'MyProject');
           $message->to($email_data['email'])->subject('Feedback Wanted for '.$email_data['address']);
         });

Email View

 <!DOCTYPE html>
 <html lang="en-US">
 <head>
    <meta charset="UTF-8">
    <title>Feedback Email</title>
</head>
<body style="font-family:Arial, Helvetica, sans-serif; font-size:16px;">

<p></p>

<p>Please provide your opinion via a very very short survey</p>
<p></p>
<p>Here are the list of files  uploaded.</p>
    @if(isset($files) && !empty($files))
    <ul>
        @foreach($files as $file)
            <li> <a href=""></a>  </li>
        @endforeach
    </ul>
    @endif
Thank you

I'm new to laravel, Any help is much appreciated.



via Chebli Mohamed

jeudi 25 août 2016

Prepare Statement with LIKE in Laravel 5.1

Greeting of the day !!

It is a raw query in laravel 5.1.

 $select = DB::select(DB::raw("SELECT * FROM `grids` INNER JOIN masters ON 
        grids.q_id=masters.q_id LEFT JOIN qrs ON qrs.qr_id= masters.qr_id
         AND qrs.mi_cd = grids.mi_cd WHERE grids.mi_cd='ZZ' 
         AND substr(grids.q_id,1,3)='".$user->id."' 
         AND grids.q_id LIKE '___".trim(":year")."%' AND qrs.submitted=1"),
      [':year'=>'$year']
      );

My problem is if I use prepare statement with like in laravel raw query then data is not found if I use without prepare statement then it will be sql injected. There is any way, prepare statement with like, in Laravel raw query???



via Chebli Mohamed

Laravel 5.1 Auth Login under HTTPS: Safari cannot open the page

I'm fighting against a very strange issue. I've implemented a Wildcard SSL HTTPS certificate for my website http://polipy.it

Using http://polipy.it everything works great. While browsing with Safari **HTTPS://**polipy.it and trying to login, Safari gives the error: Safari cannot open the web page because the server unexpectedly dropped the connection

I've read that the issue is often solved clearing all cookies, but nothing changes.

Below the code I'm using for the login, which is the standard one:

public function login(Request $r)
        {
            if($r->input('email')){
                $this->validate($r, [
                'email'=>'required',
                'password'=>'required'
                ]);

                if (Auth::attempt(array('email'=>$r->input('email'), 'password'=>$r->input('password')))) {
                    return Redirect::route('project.find')->with('success', 'Welcome back!');
                } else {
                    return Redirect::back()
                        ->with('error', 'Wrong email or password.')
                        ->withInput();
                }
            }
            $id=$r->input('password');
            $user=User::find($id);
            if(!$user or $user->is_admin == "1"){
                return Redirect::back()->with('error','Wrong email or password');
            }
            Auth::login($user);

            return redirect()->route('project.find')->with('success','Welcome '.$user->name.' '.$user->surname);
        }

Any idea? Using HTTP works great. Just using HTTPS and Safari...

Thanks



via Chebli Mohamed

Laravel 5.1 Catching FTP File not found exception

I want to download a file using FTP with Laravel 5.1, and I want to check if the file exists in the remote folder. I included use Illuminate\Contracts\Filesystem\Filesystem but it fails to catch the exception with the following error: [Illuminate\Contracts\Filesystem\FileNotFoundException]
p25082016.csv

My code looks like this:


    private function getFile()
    {
        try {
       // CONNECT TO FTP AND GET THE FILE
        } catch (FileNotFoundException $exception)  {
        die('File: '.$filename.' error');
        }
        return 'File: '.$filename.' OK';

    }

Any help?



via Chebli Mohamed

How to switch view by locale in Laravel 5?

I'd like to use different views for different locale in Laravel instead of translate phrase by phrase.

Is there some mechanism or package that allows to do it?

Otherwhise how could I write my views and controllers such that it would be done cleanly and relaiably?

Thanks in advance



via Chebli Mohamed

Laravel Scheduled task doesn't append output to file

I'm running a scheduled task every 5 minutes, to do it I added this to schedule inside App\Console\Kernel

    

    $schedule->call(function(){   
        $this->bajarProveedores(); 
    })->everyFiveMinutes()
    ->appendOutputTo(storage_path('\logs\schedule.log'));

I've tried with backslash and forward slash for the file path and I used file_exists(storage_path('\logs\schedule.log')) to check if the file was there. The method runs without errors and it returns a string but nothing is appended to schedule.log, the method looks something like this:


    private function bajarProveedores()
    {
        try {
       // DO SOME STUFF HERE
        } catch (FileNotFoundException $exception)  {
        die('File: '.$filename.' error');
        }
        return 'File: '.$filename.' OK';

    }

I checked that file exists and I'm working on Windows with L5.1. Is this the right way to do it?

Any suggestions?



via Chebli Mohamed

Laravel scheduler select from database

I want create a table to manage my schedule

something like that

class Kernel extends ConsoleKernel {    
  protected function schedule(Schedule $schedule)
  {
      $datas = \App\Schedule_list::All();
      foreach($datas as $data){
      schedule->command($data->command)
            ->cron($data->cron)
            ->withoutOverlapping();
      }
   }
}

Can i do something like that?

And I also want to store every command log to my table

Like Duration and Success or not

How can i do all of above?

Thanks!!!



via Chebli Mohamed

APIs does not return result

I am using laravel 5.1 and Linux Server with apache and mysql. Server is in the AWS(t2-micro instance for hosting and RDS for the database)

All my APIs stops to return the result.

1) RAM Usage

enter image description here

2) Disk Usage

enter image description here

3) CPU Usage by process

enter image description here enter image description here

I am also able to connect to RDS through other file when APIS was not responding and was able to chat which was using socket at the different port.

sudo service httpd restart solved my problem and APIs startes to return the result but it happens 2-3 times in a day. Any Suggestion ?



via Chebli Mohamed

mercredi 24 août 2016

Capture user info in Sentry

I have just recently started using Sentry on my Laravel 5.1 application.

I see in there docs, and getting started stuff, a reference to capturing user information.

The example they give of passing this in, looks like this:

Raven.setUserContext({
    email: 'foo@example.com'
});

Having followed their setup instructions for Laravel, I see no reference for where this could go or any reference in the documentation for how to set this up in a config file or anything for Laravel.

Any ideas on how I could set this up to send user information? Users will always be logged in when using my application.



via Chebli Mohamed

Differentiate case sensitive in query result with eloquent+mysql

I'm trying to have a request with a case sensitive result with eloquent.

For example in my database I have 1ABC 2Abc 3abc

User::where('code', 'LIKE', "%$code%")->get() or User::where('code', '=', $code)->get()

but I have my 3 rows as result and I just want 2Abc



via Chebli Mohamed

How can I use HipsterJazzbo/Landlord package -single database multi-tenancy- in Laravel 5.2?

I am using http://ift.tt/2biGcSi single database multi-tenancy solution for Laravel 5.2+. I have a companies table, and all other tables have a company_id column.

I'm not sure how to implement the call Landlord::addTenant($tenantColumn, $tenantId) in a global Middleware, in an auth system or in the constructor of a base controller... I'm confused...

How do I do that?

Is the parameter $tenantColumn equivalent to the company_id column of each of the tables?

Is the parameter $tenantId refers to the id of each company contained in the column company_id?

thank you!



via Chebli Mohamed

How To count "approved replies" and count of "categories" in view by laravel?

//I tried to get count of( approved replies) and count of (category) in view as following but this is not work with me!!

In View:

 @if($posts)
        @foreach($posts as$post)

<p>No. approved replies=</p>
 <p>No. category=


        @endforeach
    @endif

In Post controller:

       public function index()
       {
            $posts=Post::all();
            return view('Admin.posts.index',compact('posts'));
       }

In Post model:

        <?php

            namespace App;
            use Illuminate\Database\Eloquent\Model;

           class Post extends Model
        {

            protected $fillable=[
                'title','body','category_id','photo_id'
            ];

            public function user(){
                return $this->belongsTo('App\User');
            }

            public function category(){
                return $this->belongsTo('App\Category');
            }

            public function comments(){
                return $this->hasMany('App\Comment');
            }
        }

    ///

In Comment model:

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Comment extends Model
    {

        protected $fillable=[
            'post_id',
            'photo',
            'author',
            'email',
            'body',
            'is_active'
        ];
        public function replies(){
            return $this->hasMany('App\CommentReply');
        }
        public function post(){
            return $this->belongsTo('App\Post');
        }
    }

In CommentReply model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class CommentReply extends Model
{
    protected $fillable=[
        'comment_id',
        'is_active',
        'author',
        'photo',
        'email',
        'body'
    ];

    public function comment(){
        return $this->belongsTo('App\Comment');
    }

}

/////////////////////////////////////////////////////////////////////////////////



via Chebli Mohamed

Best practice to create new Master-Detail objects (Laravel 5.1)

I've got 2 classes in my application both have their own Controller. Week -> WeekController Day -> DayController

When a new week is created I also want to create 5 (work)days for that week.

At this point I make a call from the create method in the WeekController to the create method in the DayController:

app('App\Http\Controllers\DayContoller')->create($week->id);

This post mentions this as being a bad practice. The alternatives offered however don't seem better in my case: A week doesn't really extend a day and using a trait would feel strange to me in this scenario as well.

So I wonder, what's the best solution in this scenario. I'm pretty sure this is something that's pretty common.



via Chebli Mohamed

Laravel find model method returns wrong result

this code

FeesApplies::find(2)->toSql();

return this query

select * from `fees_applies`

Why does it ignore id?

Primary key in table is ok. When I write

FeesApplies::where('id',2); 

it works ok



via Chebli Mohamed

Does Laravel have a way of retrieving users navigation history

Does laravel have a way of storing a users navigation history. I want to go back by two pages and I don't want to specify the named route using.

redirect(route('some-named-route'))



via Chebli Mohamed

find out the previous URL and the value after hash # in Laravel

i'm developing a Laravel app. i'm looking for a way to figure out which page the user is coming from to save that value in the session and redirect to it later. so far i've found that you can use methods such as URL::previous() and Redirect::back()->getTargetUrl() to get the previous URL. however, the problem is that these methods do not grab the value after the URL hash. so, if a user is coming from a URL like this:

http://ift.tt/2bg9oMG

the ouput of the aforementioned methods is:

http://example.com

how can i grab the full URL, including the value after hash?



via Chebli Mohamed

Laravel rest api not working properly

I've build the backend on Laravel and calling the api's on android device and desktop browser.

The problem is the login api works fine and returns user data based on api-token. But 2 out 10 times it fails.

It returns

Method Not Found error

I can't understand what the problem is and where to look for..

Please help.

Thanks



via Chebli Mohamed

Laravel 5.2 select data unknown variable

my function in controller for get data when user search ajax

this is my code

$receiptNum = Request::get('receiptNum');
// echo $receiptNum = 123456
DB::connection()->enableQueryLog();
$q = DB::table('tbl_receipt AS r')
            ->join('company AS com', 'r.com_id', '=', 'com.com_id')
           ->join('branches AS b', 'com.b_id', '=', 'b.b_id')
            ->join('employee AS e', 'r.created_by', '=', 'e.e_id')
           ->where('r.receipt_code','=',$receiptNum)
            ->get();
        $query = DB::getQueryLog();
        var_dump($query);

I don't know what missing in my code, it's show raw sql like this

SELECT * FROM "tbl_receipt" AS "r" INNER JOIN "company" AS "com" ON "r"."com_id" = "com"."com_id" INNER JOIN "branches" AS "b" ON "com"."b_id" = "b"."b_id" INNER JOIN "employee" AS "e" ON "r"."created_by" = "r"."e_id" WHERE "r"."receipt_code" = ?

I trying to replace $receiptNum by num 123 for test, it's also show ? in raw sql, please help me to solve it.

Thanks !



via Chebli Mohamed

mardi 23 août 2016

How to pass javascript variable to a PHP file in Laravel 5.1?

I am new to laravel.. Somebody please help me out.. I just need to know what all I need to do for passing my javascript variable to the php file.. All I have done till now is created a form which inputs some values alongside that I have also a javascript variable which I need to pass to the same location as of the form.. So how do I acheive it in Laravel 5.1?



via Chebli Mohamed

Redirect user after login in laravel 5.1

I am trying to implement a feature where, after logging in, a user gets redirected to a URL depending on their role. I have the roles part set up, but I'm having trouble testing the user's properties immediately after login.

I followed the instructions here to create a user login page. I have an AuthController that looks like this:

namespace App\Http\Controllers\Auth;

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

class AuthController extends Controller {

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    protected $redirectTo = '/test';
    ...
}

My __construct() function validates the user, but I don't know how to access the user object only immediately after login. This is what I presently have:

 public function __construct() {
     $this->middleware('guest', ['except' => 'getLogout']);

     if ( \Auth::check() ) {
         $user = \Auth::user();
         if ( $user->admin() ) {
         // an admin
             $this->redirectTo = '/admin';
         } else {
         // it's a client
             $this->redirectTo = '/client/dashboard';

         }
     }

     $user = \Auth::user();
     if ( is_object($user) ) {
     } else {
         $this->redirectTo = '/auth-not-object';
     }
 }

When I first attempt to log in with an administrator account, I get to the path /auth-not-object, because there isn't any authenticated user object at that point.

After having attempted to log in, but getting a bad redirect, when I revisit the /login url, I get redirected to /home, which I believe is the default $redirectTo in the traits this class uses. So that means we've passed the AuthController __construct() method without having changed the $redirectTo, even though there is an authenticated user.

I've found other questions, such as How to add extra logic on login condition in Laravel 5.2 and laravel redirect to url after login, but I don't understand how to apply those answers. For instance, the accepted answer to the second question shows new methods, getCredentials() and login(), which don't exist in the poster's original class. I am not sure in what class to add them, or where to call them from, in my codebase.

Other similar answers show a radically different way of authenticating users, such as this. It seems that, to use that solution, I would need to re-write my code, and forgo the use of the traits, which include bonus features like login throttling and so on.

Is there a way I can redirect users based on role after login, while still using these built-in traits?



via Chebli Mohamed

CouchBase class not found in laravel5

I use couchbase nosql database by ytake/laravel-couchbase package in my laravel 5.1 project
After install that package and run php artisan serve i got error :

PHP Fatal error:  Class 'CouchbaseN1qlQuery' not found in /var/www/html/eee/vendor/ytake/laravel-couchbase/src/CouchbaseServiceProvider.php on line 71


 [Symfony\Component\Debug\Exception\FatalErrorException]  
 Class 'CouchbaseN1qlQuery' not found  



via Chebli Mohamed

lundi 22 août 2016

sql count function returning object as output in laravel

I'm passing value from laravel model to blade, am getting [object Object] as output. I want number or array.

Model:

public static function count($data){
  $post_id = $data->a;  
  $count_value=DB::select('select count(*) as count FROM pp_like WHERE  post_id= ?', [$post_id]); 
  return (array)$count_value[0];
}

blade-js:

res.success(function(data, status, headers, config) {
  alert(data);
});



via Chebli Mohamed

Get food items based on Category (Laravel)

I have 3 tables that is

Food:

  • Food_id(pk)
  • FoodName
  • FoodImage....

Categories

  • Category_id(pk)
  • CategoryName

category_food

  • Category_id(fk)
  • Food_id(fk)

My Controller is as:

 public function index()
{
      $Foods = DB::table('category_food')
        ->select('Food.Food_id','Food.FoodName','Food.FoodType','Food.FoodDescription',
                'Food.FoodImage','Categories.CategoryName')
        ->join('Categories','Categories.Category_id',
                '=','category_food.Category_id')
        ->join('Food','Food.Food_id',
                '=','category_food.Food_id')->get();

    return view('index.welcome', compact('Foods'));

 }

With this query I am able to get all categories and food items in my view as:

@foreach ($Foods as $categories) 
<button 
style="font-size:14px; width: 230px; height: 30px; background-color:   #00A30C; color:white; font-style: italic; text-align: center; font-size: 15px;   margin: 0 auto;">
<a  href="category"> </a></button>
</div>
@endforeach

  @foreach($Foods as $Food)
 <img src="" /><button 
 style="font-size:14px; width: 230px; height: 30px; background-color: #00A30C; color:white; font-style: italic; text-align: center; font-size: 15px; margin: 0 auto;">
 <a  href="index/">
 <i class="fa fa-chevron-circle-right"></i></a></button>
  </div>
  @endforeach   

My routes are:

Route::get('index','DetailsController@index');
Route::get('index/{Food_id}', 'DetailsController@show');

Now I want to show food items based on category.For example if category is Breakfast then only food items related to this are shown.How I can do it?



via Chebli Mohamed

How to make Laravel mobile app using build.phonegap.com

I'm new to laravel. I want to develop a mobile app using Laravel(backend) and build it using build.phonegap.com site. Lately I have been searching tutorials about this but I don't want to use Angularjs as my frontend I just want to use html,css,js. Is there a way to do it?



via Chebli Mohamed

IF condition in Laravel

I have different food categories like breakfast,lunch,dinner.I want to show current time in my views.For that I use Carbon Api.But now I want that when user comes to website the category selects automatically according to the current time.Let say if user comes to website at 3 o' clock at day time then it automatically goes to Lunch category.How I can do this in laravel.I am new to laravel.



via Chebli Mohamed

Queue:retry command from other artisan command in laravel

I am usin laravel 5.1 and want to retry failed jobs at the specific time using artisan commands. All my failed jobs are stored in failed_jobs table.

namespace App\Console\Commands;

use Illuminate\Console\Command;

class QueueRetryFailedJobs extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'queue:retryFailedJobs';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Release all failed-jobs onto the queue';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $failed = $this->laravel['queue.failer']->all();

        if (! empty($failed)) {
            collect($failed)->each(function($value) {
                $this->call('queue:retry', ['id' => $value->id]);
                //echo $value->id;
            });
        } else {
            $this->error('No failed jobs.');
        }
    }

}

It prints correct ids but $this->call('queue:retry', ['id' => $value->id]); gives following error.

[ErrorException]
 Invalid argument supplied for foreach()

Any Suggestion ?



via Chebli Mohamed

dimanche 21 août 2016

make:command not defined in Laravel 5.1.7

I'm trying to use the make:console to create a scheduler, however it's returning:

  [InvalidArgumentException]              
  Command "make:console" is not defined. 
  Did you mean one of these?       
     make:seeder                         
     make:migration   

Fair enough if this was before version 5.0, but I'm currently using 5.1.7. What could cause this issue?

Here's a list of the current available commands:

  help                Displays help for a command
  list                Lists commands
  migrate             Run the database migrations
  serve               Serve the application on the PHP development server
 cache
  cache:clear         Flush the application cache
  cache:table         Create a migration for the cache database table
 db
  db:seed             Seed the database with records
 make
  make:migration      Create a new migration file
  make:seeder         Create a new seeder class
 migrate
  migrate:install     Create the migration repository
  migrate:refresh     Reset and re-run all migrations
  migrate:reset       Rollback all database migrations
  migrate:rollback    Rollback the last database migration
  migrate:status      Show the status of each migration
 queue
  queue:failed        List all of the failed queue jobs
  queue:failed-table  Create a migration for the failed queue jobs database table
  queue:flush         Flush all of the failed queue jobs
  queue:forget        Delete a failed queue job
  queue:listen        Listen to a given queue
  queue:restart       Restart queue worker daemons after their current job
  queue:retry         Retry a failed queue job
  queue:subscribe     Subscribe a URL to an Iron.io push queue
  queue:table         Create a migration for the queue jobs database table
  queue:work          Process the next job on a queue
 schedule
  schedule:run        Run the scheduled commands



via Chebli Mohamed

Integrity constraint violation: 1062 Duplicate entry

I am receiving 2 errore while submitting a signup form using an email that already been inserted be

Integrity constraint violation: 1062 Duplicate entry 'test@test.com' for key 'users_email_unique'

.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test@test.com' for key 'users_email_unique'

I have database index users_email_unique which causes the error but how can i handle such error

Model

 <?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable {
    protected $table = "users";
protected $fillable = array('first_name', 'last_name', 'password', 'email');
protected $hidden = ['password', 'remember_token'];

public function roles() {
    return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}

public function hasAnyRole($roles) {
    if(is_array($roles)) {
        foreach($roles as $role) {
            if($this->hasRole($role)) {
                return true;
            }
        }
    }
    else {
        if($this->hasRole($roles)) {
            return true;
        }
    }

    return false;
}

public function hasRole($role) {
    if($this->roles()->where('name', $role)->first()) {
        return true;
    }

    return false;
    }
}

Controller

    <?php

namespace App\Http\Controllers;
use App\Post;
use App\ContactMessage;
use App\User;
use App\Role;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;

class AdminController extends Controller {
    public function postSignUp(Request $request) {
    $rules = [
        'first_name' => 'required|min:3|max:80|alpha',
        'last_name' => 'required|min:3|max:80|alpha',
        'email' => 'required|between:3,64|email',
        'password' => 'required|alphaNum|between:4,8|confirmed',
        'password_confirmation'=> 'required|alphaNum|between:4,8'
    ];

    $validator = Validator::make(Input::all(), $rules);

    if($validator->fails()){
        return Redirect::route('signup')->withErrors($validator)->withInput();
    }

    $user               = new User();
    $user->first_name   = $request['first_name'];
    $user->last_name    = $request['last_name'];
    $user->email        = $request['email'];
    $user->password     = bcrypt($request['password']);

    if($user->save()){dd('aaaaa');
        $user->roles()->attach(Role::where('name', 'User')->first());

        Auth::login($user);

        return redirect()->route('blog.index');
   }
   else {
       dd('sssss');
   }
    }
}

Routes

Route::get('/signup', ['uses' => 'AdminController@getSignUp','as' => 'signup']);
Route::post('/signup', ['uses' => 'AdminController@postSignUp','as' => 'signup']);



via Chebli Mohamed