samedi 31 octobre 2015

How do I get the name of a Job in larval 5

I've tried $this->getName() inside the laravel Job

This is my sample job class

class PrepareCustomersSearchExportJob extends Job implements SelfHandling, ShouldQueue
    {
    use InteractsWithQueue, SerializesModels;

    private $path;
    private $filename;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($path, $filename)
    {
        $this->path = $path;
        $this->filename = $filename;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
             echo  “Name  = “. $this->getName();    
    }
}

But the method above tells me getName() isn't defined.

Thanks for your help.



via Chebli Mohamed

What is the advantage of using constructor injection in a repository in laravel 5?

I am building a laravel 5 app and I have a repository like below:

use App\Unit

class UnitRepository implements IUnitRepository
{
     public function get_all_units()
    {
        return Unit::all();
    }

    // More methods below
}

In about 6 methods in the repository, I am doing something like Unit::someMethod. Now I am wondering if I should use constructor injection like so

class UnitRepository implements IUnitRepository
{
    public function __construct(Unit $unit){ 
        $this->unit = $unit
    }

    public function get_all_units()
    {
        return $this->unit->all();
    }

    // More methods below
}

So what would be the advantage of using constructor injection in my case. Is they some kind of performance improvement considering that I am using the facade in about 6 methods?

Appreciate help



via Chebli Mohamed

Laravel 5 comment block

I found before few months some video on Laracast which explain comment blocks can replace some functionality in Laravel 5. I think it was different way of defining properties or something like that, it was new feature in Laravel 5, but I can't find now that video, anyone know about it?



via Chebli Mohamed

How to inject dependencies to a laravel job

I'm adding a laravel job to my queue from my controller as such

$this->dispatchFromArray(
    'ExportCustomersSearchJob',
    [
        'userId' => $id,
        'clientId' => $clientId
    ]
);

I would like to inject the userRepository as a dependency when implementing the ExportCustomersSearchJob class. Please how can I do that?

I have this but it doesn't work

class ExportCustomersSearchJob extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels, DispatchesJobs;

    private $userId;

    private $clientId;

    private $userRepository;


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($userId, $clientId, $userRepository)
    {
        $this->userId = $userId;
        $this->clientId = $clientId;
        $this->userRepository = $userRepository;
    }
}



via Chebli Mohamed

Laravel 5 User class properties not accessible for sending Email after account creation

I have a problem where I can't put in the variables into the Mail::send() function in laravel. Please see the following code:

$first_name = $request->input('first_name'),
$email = $request->input('email'),

//Create account

User::create([
    'first_name' => $first_name,
    'last_name' => $request->input('last_name'),
    'email' => $email,
    'password' => bcrypt($request->input('password')),
]);

//Send email to user

Mail::send('emails.test', ['fname' => $first_name], function($message)
{
    $message->to($email)
            ->subject('Welcome!');
});

return redirect()
    ->route('home')
    ->with('info', 'Your account has been created and an authentication link has been sent to the email address that you provided. Please go to your email inbox and click on the link in order to complete the registration.');

For some reason the code breaks when it gets to the send email because I receive the error and the data is sent to the database. Why is the variable no longer accessible afterwards?

Any help would be greatly appreciated. Thank you



via Chebli Mohamed

Mass Assignment Expection with create and update methods

I have strange issue while using create or update methods on laravel tinker although i added $fillable array

table fields as follows

  1. id
  2. title
  3. body
  4. published_at
  5. timestamps

model as follows

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = ['title','body'];
}

command line i typed

$article = App\Article::create(['title' => 'ready']);



via Chebli Mohamed

3 relation how database should look and how to create queries wtih Laravel Eloquent?

I have 3 relations:

project can have many tasks and tast have one project

user can have many tasks and task can have many users

user can have many projects and project can have many users --> this relation I already have in pivot table project_user

How other tables should look like and how can I query them to take all tasks for current logged user and some project id ?



via Chebli Mohamed

Phpunit testing Laravel 5.1 restful controller

I have been stuck on that issue for a little while, no other question on SO helped me.

I am using Laravel 5.1 and phpunit to test a restful controller. My testing code looks as such:

$this->post('/api/book', [ 'title' => 'my book'])
  ->assertResponseOk();

And the target controller has, among others, the following code:

Log::debug('title: ' . $request->json('title'));

i.e. on the testing side I expect to use the TestCase::post() method to send a request and on the server side I expect to use the Request::json() method to read from the request. However when I look at the logs I see the following empty string

[2015-10-31 17:26:01] testing.DEBUG: title:   

This is showing that either my testing code is not setting the right data in the request or that my server code is not reading the request properly. By the way, the server is failing a bit further as well, reflecting the missing title value in the logs.

I am also using a Firefox plugin, RESTClient, to manually test my web app and I had to set properly the body (using double-quotes around the title key, respecting strictly the JSON specs) to make sure the server code work. So the exact format is a trail I followed, without success so far.

So my question is, what is the most recommended code to use for a RESTful controller on the testing and on the server sides, in Laravel 5.1?



via Chebli Mohamed

jasper report integrate in laravel 5

Hi what a integration and thanks for this tutorial.I have a proble with this integration in Laravel 5:

Exception in JasperPHP.php line 178: Your report has an error and couldn't be processed! Try to output the command using the function output(); and run it manually in the console.

Code where Exception happens:

\JasperPHP::process(
'D:\wamp\www\laravel-Project\reports\center_report.jasper',
false,
array("pdf", "rtf"),
array("php_version" => phpversion()),
$database
)->execute();



via Chebli Mohamed

Laravel 5 : check image type validation only if uploaded

I am creating a form in laraval 5 which has a product name, product main image image and secondary image. Both the image field are optional, here is my input fields

            <div class="form-group {{ ($errors->has('title')) ? 'has-error' : '' }}">
                <label>Title *</label>  
                <input class="form-control validate[required]"  name="title" type="text"  value="{{ Input::old('title') }}">
                {{ ($errors->has('title') ? $errors->first('title') : '') }}
            </div><div class="form-group">
                <label for="featured_image">Cover Image <small>(optional)</small></label>
                    <input type="file" placeholder="" id="featured_image" name="featured_image" >
                    <small class="description"> Maximum file size: 2 MB.</small>                
                    {{ ($errors->has('title') ? $errors->first('featured_image') : '') }}
            </div>
             <div class="form-group">
                <label for="gallery_images">Gallery Images <small>(optional)</small></label>

                    <input type="file" placeholder="" id="gallery_images" name="gallery_images[]" multiple="" >
                    <small class="description">Maximum file size: 2 MB.</small>                
                    {{ ($errors->has('title') ? $errors->first('gallery_images') : '') }}
            </div>

and my validation in request file is

public function rules()
    {
        return [
            'title'              => 'required|min:5',
            'featured_image'     => 'mimes:jpeg,png,jpg|max:2048',
            'gallery_images'     => 'mimes:jpeg,png,jpg|max:2048'
        ];
    }

but it always check for the image upload whether it is uploaded or not. Which is incorrect, the image type was checked only when images were upload else not.

Thank you.



via Chebli Mohamed

Using the Laravel test client with Behat

Is it possible to use the Laravel test client with Behat? It seems to be better for testing REST APIs than Mink so I don't want to use the Laracasts integration. Is there a way I can use the same test client in Behat tests? If there is I can't find it on Google.



via Chebli Mohamed

Create subquery in Laravel - Query builder

I try to create a sub query. For now, my two queries are :

select `key` from messages group by `key`;

and

select * from messages where `key` = 'KEY_RECUP_AU_DESSUS' order by created_at DESC LIMIT 1;

The aim is to highlight my table messages all elements grouped by key and keeping the last element ( created_at desc)

Thank you



via Chebli Mohamed

Laravel 5 Social Authentification (keep session alive)

I am currently developing a web application with Laravel 5.0 and I authenticate my users with Facebook and Twitter using the socialite plugin.

Everything is working well now, I actually already made a post about it when I was struggling with it when I started. So if you want to see the code I'm running you can refer to my previous article.

But now I would like to keep those sessions "alive"? , I don't want to click on the login button everyday and I am having a hard time finding information about it...

The thing is I am not even sure if I look at the right place.. because I am a real newbie in this area and I don't know If I should read more about the Facebook and Twitter SDK or should I look on the Laravel side only ?

I've must have read the Laravel authentication chapter a hundred times but I really don't know where to start. Remembering a token sounds like the way to go but I have no idea whatsoever how to implement it in my current environment. This is the method provided by Laravel:

if (Auth::attempt(['email' => $email, 'password' => $password], $remember))
{
 // The user is being remembered...
}

But when we use the socialite plugin we have to log in the user with the Auth::loginUsingId(id); method, am I wrong ? So how can we remember the user with this method ? Is it possible ? Is it the way to go ?

I hope my problem is clear enough. So if anyone could tell me where should I focus my researches that would be great !



via Chebli Mohamed

vendredi 30 octobre 2015

Laravel 5-TokenMismatchException in VerifyCsrfToken.php line 53: SOS CALL

This error is driving me nuts. I'm trying to create a retrieve password form and this error keeps getting thrown when I submit it. Token is definitely being provided, so I don't know what is wrong. This happens only on my local so far. It doesn't happen on production. And at the same time, not sure if it's related, I get

InvalidStateException in AbstractProvider.php line 191 

when i try to login with socialite(google & fb). One tends to occur when the other occurs. If I get tokenMismatch from submitting the form and then try to login, I get this error.

Anyway here's the form. I really need help here

{!! Form::open(['method'=>'post', 'action'=>'PasswordRetrieveController@getUser','id'=>'retrieve-pw-form'])!!}


    <div class='form-group'>
        {!! form::label('email','Email Address')!!}
    {!!Form::text('email','',['class'=>'form-control','type'=>'email','required'=>'required'])!!}

   </div>

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

Here's the controller. It never hits my getUser function. Just throws the tokenMismatch error.

<?php
namespace App\Http\Controllers;

use App\User;
use App\SecurityQuestions;
use Mail;
use Redirect;
use Illuminate\Http\Response;
use Illuminate\Http\Request;

class PasswordRetrieveController extends Controller{

public function index(){
    return view('password.index');
}

public function getUser(Request $request){
    $email = $request->get('email');
    $user = User::where('email',$email)->first();
    if ($user == null){
        return Redirect::back()->with('message','This email does not exist');
    }
    if(($user->password == null) && (!empty($user->provider))){
        return Redirect::back()->with('message','A password for this email does not exist. Log back in with facebook or google');
    }
    else{
        $tmp_pw = $this->generate_tmp_pw($user);

    return Redirect('password.security_question_1');
    }
}

public function security_questions(){
    echo 1 ;exit;
}

private function generate_tmp_pw($user){
    $tmp_pw= str_random(10);

    $user->tmp_password = $tmp_pw;
    $user->save();
    return $tmp_pw;
}

}



via Chebli Mohamed

how i can open admin page in other tab with redirect::to?

how i can open admin page in other tab (target blank) when user login?

In my controller after validate return this:

return Redirect::to('/adminpanel');



via Chebli Mohamed

How to make a rest api with Facebook Authentication

I want to make an iOS app that need to communicate with a webservice/restful api to get data from a Mysql DB. Instead of implement my own user login module in my iOS app I want to use Facebook sdk/api. I'm using Laravel 5 to make my rest api (I'm new to laravel/php). So my question is how do I authorize the logged in facebook user?

I was thinking when a Facebook user login via my iOS app I save the required Facebook users data in a table called "users" with a post request from the iOS app. And let say a user has many images. So if I want to get all images for a certain user from my iOS app I will send the access-token to my webservice and from my webservice I'll find users id by using the access_token (making a post request to facebook api to get user details) and with the users id I can get the images that belongs to.

As said I'm new to all these technologies so if I'm wrong please correct me and help me further - Thank you

PS: I have read something called Social Authentication in laravel, but haven't digged deeper into it.



via Chebli Mohamed

how to get city inside a especific country with Faker extension

i'm working with fzaninotto/Faker extension in Laravel 5 to populate my database, the thing is that I have a table countries and a table Cities so, I call $faker->country but how can I get a city that is inside that country? I don't want for example that Bogotá belongs to EEUU Thank you!



via Chebli Mohamed

Form Validation messages Vs Language in Laravel 5

After reading the docs, I've understood the strucutre in resources/lang/xx/validation.php to add custom error messages.

'custom' => [
    'name' => [
        'required' => 'Please fill the name of the company'
    ]
],

My problem here is that after setting this up, I won't be able to use a field called name to another resource, for instance a Please fill out your name message. When overriding the method messages() inside the FormRequest, I'm able to be more specific in these messages, but then I lose the Language customization.

My question is: How can I go about setting up custom messages for different Form Requests and still keep the language system working in my favor?



via Chebli Mohamed

PHP Speeding Up MySql Queries

I am using the Laravel PHP Framework.

Say I have some queries like this:

public function order($orderby){
        \DB::connection()->disableQueryLog();

        if($orderby == "level"){
            $clan = Clans::orderBy('level', 'DESC')
            ->orderBy('exp', 'DESC')
            ->paginate(100,['id', 'clanid', 'name', 'level', 'exp', 'warwinpercent', 'warswon', 'playercount', 'score']);
        }elseif($orderby == "score"){
            $clan = Clans::orderBy('score', 'DESC')
            ->paginate(100,['id', 'clanid', 'name', 'level', 'exp', 'warwinpercent', 'warswon', 'playercount', 'score']);
        }elseif($orderby == "warwinpercent"){
            $clan = Clans::orderBy('warwinpercent', 'DESC')
            ->where('warswon', '>=', '100')
            ->paginate(100,['id', 'clanid', 'name', 'level', 'exp', 'warwinpercent', 'warswon', 'playercount', 'score']);
        }else
            $clan = Clans::paginate(100,['id', 'clanid', 'name', 'level', 'exp', 'warwinpercent', 'warswon', 'playercount', 'score']);

        \DB::connection()->enableQueryLog();

        return view('clans.index')->with('clan', $clan);
    }

These are taking around 10-15 seconds to run.

I have one like this:

public function index(){

        $clan = Clans::orderBy('clanid', 'ASC')
            ->paginate(100,['id', 'clanid', 'name', 'level', 'exp', 'warwinpercent', 'warswon', 'playercount', 'score']);

        return view('clans.index')->with('clan', $clan);
    }

Which loads almost instantly.

How come the first 3 are taking so much longer than the last one? I added an Index for all the variables I need to search through in my table but it is still taking ages for it to work. Do I need to do anything on the MySql side to make it rebuild the index? I already tried Optimize table and I restart the MySql Service multiple times as well..

If it isn't possible to speed them up then is there a simple way I can show a loading animation to the user while it loads the page?

Thanks!



via Chebli Mohamed

Laravel 5 Eloquent: Foreign key to same table belongsTo() not working

I have a "categories" table. A category can have many sub-categories The schema is ,

    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('category_id')->unsigned();
        $table->string('image');
        $table->timestamps();

        $table->foreign('category_id')->references('id')->on('categories');
    });  

And the relationship inside model class looks like,

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

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

Now the child() method is working fine, But the parent() method is returning null.
So, $category->parent returns null



via Chebli Mohamed

Cannot get the twig bridge working in laravel

So, i am giving laravel a try however i want to use twig instead of blade.

http://ift.tt/1ExNwnB

This guy wrote a "bridge" for it but i cannot get it to work.

I have added to the provider array in /config/app.php:

   ...
  'TwigBridge\ServiceProvider'
]

I've added to the aliases array in /config/app.php:

    'Twig' => 'TwigBridge\Facade\Twig',
],

But then in the readme it just shows these lines but doesn't really say where to put them:

Twig::addExtension('TwigBridge\Extension\Loader\Functions');
Twig::render('mytemplate', $data);

Without them in my routes.php file I have:

Route::get('/', function () {
    return view('hello.html.twig');
});

But all i get when i access said route is a twig error page saying

1 - in FileViewFinder.php line 137
2 - at FileViewFinder->findInPaths('hello.html.twig', array('/var/vhost/project101/resources/views')) in FileViewFinder.php line 79
3 - at FileViewFinder->find('hello.html.twig') in Factory.php line 151

So I can only assume I have missed something, but really don't know what.

Any laravel fans out there who managed to get twig working?



via Chebli Mohamed

Laravel 5.1 - return eloquent model with multiple relationships

I have the following models Show, Presenter, Image.

Shows can have multiple presenters. Presenters have one image.

I can do this to get a presenter with their image:

$presenter = Presenter::with('image)->find(1);

And I can do this to get a show with presenters:

$show = Show::with('presenters')->find(1);

Is there a way I can return a show with presenters and their image in one statement?



via Chebli Mohamed

Should I check for permission on controller if already checking on middleware?

I created a middleware that checks if the user is authorized to perform an action and added this middleware to the routes that I want to protect like this:

// VerifyPermission middleware

class VerifyPermission {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param $permission
     * @return mixed
     */
    public function handle($request, Closure $next, $permission)
    {
        $user = auth()->user();

        if (auth()->check() && $user->hasPermission($permission))
        {
            return $next($request);
        }

        return redirect('/');
    }
}

// Routes

Route::patch('company/{id}', ['as' => 'updateCompany',
                              'uses' => 'SettingsController@updateCompany',
                              'middleware' => 'permission:manage_company']
);

My question is, is it necessary to make another check on updateCompany or is the middleware check sufficient?

public function updateCompany()
{
    if(Auth::user()->hasPermission('manage_company'))
    {
        // Updates Company
    }   

    return abort(403, "Unauthorized");
}



via Chebli Mohamed

PhantomJS does not run JavaScript code

I'm using Laravel with Vagrant. I need to run acceptance test using Codeception and PhantomJS. Everything seems to be fine except running JS code.

I have a registration form that uses a little JS code to prevent robots from registration:

<script type="text/javascript">
        $(function() {
            $('.form-horizontal').append('<input type="checkbox" name="human" value="1" checked="checked">');
        });
    </script>

This is what I do.

1) I run phantomjs:

B# phantomjs --webdriver=5555

2) Start acceptance test:

vendor/bin/codecept run acceptance RegisterCept

Of course test fails because PhantomJS does not execute JS code and without it registration can not be completed. What am I doing wrong? Config file:

class_name: AcceptanceTester
modules:
    enabled:
        - WebDriver:
            url: http://localhost
            browser: phantomjs
            port: 4444
            capabilities:
                javascriptEnabled: true
                webStorageEnabled: true
                unexpectedAlertBehaviour: 'accept'
        - Laravel5:
            environment_file: .env.testing
        - \Helper\Acceptance

I'm using Travis. Test also fails. My .travis.yml:

language: php
php:
  - 5.5
  - 5.6

services: postgresql

addons:
  postgresql: "9.3"

install:
  - composer install

before_script:
  - cp .env.testing .env
  - php artisan migrate --seed --env="testing"
  - php vendor/bin/codecept build
  - phantomjs --webdriver=4444 2>&1 >/dev/null &
  - sleep 5

script: php vendor/bin/codecept run



via Chebli Mohamed

Laravel on sorting related model?

I know from laravel documentation that I can do eager loading like:

$records = (new Route)->with('country')->get();

But when I execute this:

    $records = (new Route)->query()->with('country')->orderBy('country.name', 'asc')->paginate();

I get this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'country.name' in 'order clause' (SQL: select * from `routes` order by `country`.`name` asc limit 2 offset 0)

How I can sort on related model ? How can I force laravel to load joined tables?



via Chebli Mohamed

Calculating sum in pivot table in laravel 5

I have 3 tables: demands,products and receives. To link demands and receives, I am using following schema for receives table instead of pivot table (i.e demand_receive). Let the instance of receives table looks like below.

|**id** | **demand_id** | **receive_note** | **receive_date** |
|R1     |D2             |                  |10/29/2015        |
|R2     |D2             |                  |10/30/2015        |

pivot table demand_product looks like below.

 |**demand_id** |**product_id** |**demand_quantity** |
 |D2            |P1             |100                 |
 |D2            |P2             |500                 |
 |D2            |P3             |1000                |

To trace the receiving products of the demand, I have made pivot table product_receive which looks like below.

 |**receive_id** |**product_id** |**receive_quantity** |
 |R1             |P1             |50                   |
 |R2             |P1             |40                   |
 |R2             |P2             |500                  |

Here, I am trying to trace partial receive of demand. What I actually want is to find the total receive quantity of an individual product of a given demand id so that the result can be used to control receive quantity(say total_received_quantity) in the views.

For example:

for demand id D2, 
total_receive_quantity of P1=90
total_receive_quantity of P2=500
total_receive_quantity of P3=0

How can I achieve above answer in laravel? Thanks in advance.



via Chebli Mohamed

My laravel application on subdomain on localhost and this url is app.localhost.com but its not works in subdomain properly how to set this .htaccess

my .htaccess is on root directory

RewriteEngine On
RewriteBase /
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

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



via Chebli Mohamed

Laravel event listeners undefined property error with ShouldQueue

I have an event setup within my application that sends out an activation email upon the user signing up. It works perfectly without the ShouldQueue interface. However, when I add implements ShouldQueue, I get undefined property error:

Undefined property: App\Events\User\UserCreated::$user

The code I am using is as follows:

<?php

namespace App\Listeners\User;

use App\Events\User\UserCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repos\Email\EmailTemplateRepoInterface;
use App\Repos\User\UserRepoInterface;
use Request, Mail, DbView;

class UserCreatedEmail implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(EmailTemplateRepoInterface $template)
    {
        $this->template = $template;
    }

    /**
     * Handle the event.
     *
     * @param  UserCreated  $event
     * @return void
     */
    public function handle(UserCreated $event)
    {
        $user = $event->user;

        if($user)
        {
            if(!$user->status)
            {
                $user->activation_url = Request::root().'/activate/'.$user->activation_code;
                $template = $this->template->findTemplateByName('new_user_activation');
                $userArr = $user->toArray();
            }

            Mail::queue([], [], function ($message) use ($template, $userArr) 
            {
                $message->to($userArr['email'])
                    ->subject($template->subject)
                    ->setBody(DbView::make($template)->with($userArr)->render(), 'text/html');
            });
        }
    }
}

Can anyone explain why this happens when I try to queue the email?



via Chebli Mohamed

Laravel 5 setup git repo for multiple developers

I've done lot of Google but still looking for solution, I'm working on Laravel5 project & wants to set it up with GitHub so multiple developer can work on it.

I've install Laravel & place in a repository on Git, Now I cloned it on my local machine & another developer also clone that repository in his machine and start working.

But issue is that, I have installed a package for HTML forms in my machine by composer & push my code to github. But when another developer pull the repository then his code is break because composer.js is updated for that package but actually that HTML package is not exists on his machine.

Can anyone help me to short out this, or is there any way so we ignore vendor folder, composer.js, app.php etc files during git Push?



via Chebli Mohamed

jeudi 29 octobre 2015

Many to many relation for a user to regions and roles

In my application there was a many to many relation between a user and regions, and the same for user and roles. Previously a user had many regions under one city. Also, a user had many roles in one city, primarily Admin as the second role.

Now there's a change in the system. A user can have two roles in multiple city.

For example: User A has 4 regions. 2 regions belong to city X and 2 belong to city Y. And user has two different roles in city X and city Y.

My current schema is below:

User
belongsToMany('App\Region', 'user_region', 'user_id', 'region_id');
belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');

How can I implement this new system with my existing schema? v1 is already on production. I need to change this in v2.



via Chebli Mohamed

How to catch global exceptions in laravel 5 genarated by the EvanDarwin/Laravel-JSend pacakge?

I am working on a RESTful application using Laravel 5 and I am trying to catch exceptions and generate an appropriate response. I am also using the EvanDarwin/Laravel-JSend package so that all the API responses are in JSend JSON format.

Right now I am trying to catch the TokenExpiredException which arises when the given token is expired of course. So I tried this in the Handler.php:

if($e instanceof TokenExpiredException)
{
    return jsend()->error()
          ->message("Token Expired")
          ->code(403)
          ->data([null])
          ->get();
}

But I am still not able to catch this exception and give back a JSON response. Although I am able to do this for other exceptions like:

if ($e instanceof ModelNotFoundException) {
    $e = new NotFoundHttpException($e->getMessage(), $e);

    return jsend()->error()
              ->message("404 Model Not Found")
              ->data([null])
              ->get();
}

And:

if ($this->isHttpException($e))
{       
    if($e instanceof NotFoundHttpException)
    {
        return jsend()->error()
              ->message("404 Route Not Found")
              ->data([null])
              ->get();
    }
    return $this->renderHttpException($e);
}

How to handle other exceptions in Laravel?



via Chebli Mohamed

how to configure laravel 5 in ubuntu 12.04?

i installed laravel5 in Ubuntu 12.04 and I have updated version of xampp with php 5.5.1. Actually i don't want to make any mistake thats why i asked this questions because most of the time i had face pdo exception plus sql server errors only because of wrong config settings.

Below is my app.php file

return [

/*
 Application Debug Mode

*/

'debug' => env('APP_DEBUG', false),

/*
 Application URL

*/

'url' => 'http://localhost',

/*
 Application Timezone

*/

'timezone' => 'UTC',

/*
   Application Locale Configuration

*/

'locale' => 'en',

/*
 Application Fallback Locale

*/

'fallback_locale' => 'en',

/*
 Encryption Key

*/

'key' => env('APP_KEY', 'SomeRandomString'),

'cipher' => 'AES-256-CBC',

/*

*/

'log' => 'single',

/*

Autoloaded Service Providers

*/

'providers' => [

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

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

],


'aliases' => [

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

],

];

Below is my database.php file.

return [

/*

*/

'fetch' => PDO::FETCH_CLASS,

/*

*/

'default' => env('DB_CONNECTION', 'mysql'),

/*
 Database Connections

*/

'connections' => [

    'sqlite' => [
        'driver'   => 'sqlite',
        'database' => storage_path('database.sqlite'),
        'prefix'   => '',
    ],

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

    'pgsql' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public',
    ],

    'sqlsrv' => [
        'driver'   => 'sqlsrv',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
    ],

],


'migrations' => 'migrations',



'redis' => [

    'cluster' => false,

    'default' => [
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ],

],

];



via Chebli Mohamed

Where to put data for select boxes in Laravel?

If I have table in database like this:

users
    id
    username
    status

and status can be:

status 0 - not active 1 - active 2 - banned

where should I put statuses, i have some possibilities:

  1. in repository pattern for users
  2. in User Eloquent class
  3. in helpers
  4. in database (sometimes I would create 50 more tables for this and I dont think this is good idea)

?



via Chebli Mohamed

Laravel PHP Loading Animation

I am using the Laravel framework for my PHP Webapp.

I am executing some SELECT queries which can take a few seconds to run. My Controller looks like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Clans;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class ClansController extends Controller
{
    public function index(){
        \DB::connection()->disableQueryLog();

        $clan = Clans::paginate(100,['id', 'clanid', 'name', 'level', 'exp', 'warwinpercent', 'warswon', 'playercount', 'score']);

        \DB::connection()->enableQueryLog();


        return view('clans.index')->with('clan', $clan);
    }



    public function order($orderby){
        \DB::connection()->disableQueryLog();

        if($orderby == "level"){
            $clan = Clans::orderBy('level', 'DESC')
            ->orderBy('exp', 'DESC')
            ->paginate(100,['id', 'clanid', 'name', 'level', 'exp', 'warwinpercent', 'warswon', 'playercount', 'score']);
        }elseif($orderby == "score"){
            $clan = Clans::orderBy('score', 'DESC')
            ->paginate(100,['id', 'clanid', 'name', 'level', 'exp', 'warwinpercent', 'warswon', 'playercount', 'score']);
        }elseif($orderby == "warwinpercent"){
            $clan = Clans::orderBy('warwinpercent', 'DESC')
            ->where('warswon', '>=', '100')
            ->paginate(100,['id', 'clanid', 'name', 'level', 'exp', 'warwinpercent', 'warswon', 'playercount', 'score']);
        }else
            $clan = Clans::paginate(100,['id', 'clanid', 'name', 'level', 'exp', 'warwinpercent', 'warswon', 'playercount', 'score']);

        \DB::connection()->enableQueryLog();

        return view('clans.index')->with('clan', $clan);
    }


    public function showclan($id){
        $clan = Clans::find($id);

        return view('clans.clan' , compact('clan'));
    }


}

What I am trying to do is while that is all running I want a loading animation to be shown to the user. When the page is loaded then I want the page to be shown.

How can I go about achieving this? I looked into JQuery and PHP stuff but they only show when the full page has already loaded (I tried them in the View).

Thanks for any help you can provide.



via Chebli Mohamed

php tiny url not linking correctly. My website url gets appended to tinyurl.com and I get a 404 error

This is my tiny url function

private function getTinyUrl($url) {
    return file_get_contents("http://ift.tt/x0MBwI".$url);
}

the output is something like http://ift.tt/1P8PArG so thats good.

But when I use the url, it takes me to

http://ift.tt/1Rhe2Gt

and i get a 404 not found. What to do?



via Chebli Mohamed

Why my page us not styling using bootstrap?

I am trying to use Laravel 5.1. I included bootstrap 3.3.5 on the top. Then I created a div with a class of "container".

I used the css like this

<div class="form-group">

    <label for="control_3">Tell me about your self</label>

    <textarea class="form-control" name="control_3" cols="50" rows="10" id="control_3"></textarea>

</div>

I am sure the Css and the .js for bootstrap are included as I validated that using my page's source code.

But the page still looks bad "not using styling"

What would be the cause off this?



via Chebli Mohamed

Laravel phpunit tests - loadEnvironmentFrom not loading correct ENV

I'm having trouble loading the correct ENV file for Laravel 5.1 integration testing.

I found when I create a user/rollback DB, etc... It is acting on my app local database, and not my test database.

I am setting the env on ApplicationCreation with $app->loadEnvironmentFrom('.env.testing');, and it seems to be properly setting:

die('environment ' . $app->environment()); 

Outputs "testing".

So I'm not sure why it's running my test suite CRUD operations on my local DB, and not the testing environment.

TestCase.php:

class TestCase extends Illuminate\Foundation\Testing\TestCase
{
    protected $baseUrl = 'http://ift.tt/1Ml506V';

    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

        $app->loadEnvironmentFrom('.env.testing');

        die('environment ' . $app->environment()); //"testing"

        return $app;
    }
    ...

.env.testing:

APP_ENV=testing
APP_DEBUG=true
APP_KEY=my_key

DB_HOST=localhost
DB_DATABASE=testbench
DB_USERNAME=root
DB_PASSWORD=''

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

UserTest:

class UserTest extends TestCase
{

    public function setUp()
    {

        parent::setUp();

        Artisan::call('migrate:reset');

        Artisan::call('migrate');

        Artisan::call('db:seed');

    }

    ... test functions here



via Chebli Mohamed

laravel 5 where() not working

i have two tables, categories and subcategories, and each item in subcategories belongs to categories by foreign key "category_id".

i have two models one for categories and one for subcategories, and one controller.

my category model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    //
    public function subcategories()
    {
        return $this->hasMany('\App\Subcategory');
    }

}

subcategory model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subcategory extends Model
{
    protected $fillable = [

        'sub_category_name',
        'category_id'
    ];
}

and CategoriesController

<?php

namespace App\Http\Controllers;

use App\Category;
use App\Subcategory;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CategoriesController extends Controller
{
    //return array of categories
    public function categories ()
    {

        $categories =  Category::where('category_name', '=', 'Construction Machines')->subcategories;
        return $categories;
    }
}

question is when i do Category::find()->subcategories i get the expected results. but when i use where(), it gives me Undefined property: Illuminate\Database\Eloquent\Builder::$subcategories error



via Chebli Mohamed

How to use angular in .php file while rendering a laravel view

I am new to laravel and angular . I am trying to render a view which is a php file. The .php file is being rendered but the angular expression inside it is not being evaluated.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="http://ift.tt/1K1B2rp" >
<script src="http://ift.tt/1InYcE4">     </script>
<script src='public/AngularSorter.js'></script>
<script src = "http://ift.tt/1MrEm0Z"> </script>
</head>



<body ng-app = 'store'>
<div ng-controller ='SorterController as sorter'>
 <p>
   {{ 4+4 }}

 </p>
</div>
</form>
</body>
</html>

the route is like this

Route::get('/', function () {
 return view('Home');
  });

Am I missing something? I tried renaming the php file to .html but it doesn't work. why can't the view render .html file??



via Chebli Mohamed

Laravel ServiceProvider bound arguments not passed through

I have the following ServiceProvider:

use App\Api\Session;

class ApiServiceProvider extends ApiServiceProvider
{
    public function register()
    {
        $accessKey = 'accessKey';
        $secretKey = 'secretKey';
        $userAgent = 'userAgent';
        $domain = 'domain';

        $this->app->bind('App\Api\Session', function (Application $app) use ($accessKey, $secretKey, $userAgent, $domain) {
            return new Session($accessKey, $secretKey, $userAgent, $domain);
        });
    }
}

As I'd like to be able to inject the App\Api\Session class into my controllers/commands, rather than having to create new instances and pass in the $accessKey, $secretKey, $userAgent and $domain each time I want to use them. For example:

use App\Api\Session;

class SessionController
{
    public function __construct(Session $session)
    {
        $this->session = $session;
    }

    public function store()
    {
        $response = $this->session->create($credentials);

        // etc...
    }
}

I thought this approach would work however I don't think I have bound this correctly as none of the $accessKey, $secretKey, $userAgent and $domain are set whenever I try and do anything from within my controller.

Is this even possible or am I just going about it the wrong way?

Thanks in advance.



via Chebli Mohamed

laravel 5 route jquery sortable

I'm using Laravel 5 and use the jquery sortable: http://ift.tt/1eMUFGW

In my sortable.blade.php I have the following script:

  <script>
      $(function() {
          $('#sortMe').sortable({
              update: function(event, ui){
                  var postData = $(this).sortable('serialize');
                      console.log(postData);

                      $.ajax({
                          data: postData,
                               type: 'POST',
                               url: '{{ URL::to('sortable') }}'
                            });
                        }
                    });
                });
  </script>

Further the sortable.blade.php contains the following html

<div id="sortMe">
     <div id="item_1">Test1</div>
     <div id="item_2">Test2</div>
     <div id="item_3">Test3</div>
     <div id="item_4">Test4</div>
     <div id="item_5">Test5</div>
</div>

My route file contains the following:

Route::post('sortable', 'Sortable\SortableController@sortable');

In my SortableController I have at the moment an empty function:

public function sortable() {}

At the moment when I move one item within the div "sortMe", the firebug show me the moved items list : item[]=1&item[]=2&item[]=4&item[]=3&item[]=5 and give me an exception: POST http://localhost/myProject/sortable 500 Internal Server Error 261ms

Any ideas why I get this error? The purpose is that the after moving an item the sortable() function will be called which takes the moved items and save the order of the items within the database. At the moment it seems that there is a problem when calling the sortable() function. Thank you for any help!



via Chebli Mohamed

Removing Session and Redirect from Laravel 5 RESTful API

I'm on my way to building a restful API using Laravel 5.1 and it passed my mind disabling completely services that are incompatible with the restful way.

So, I tried to go to config/app.php and I removed:

  • Illuminate\Session\SessionServiceProvider::class, from providers
  • 'Redirect' => Illuminate\Support\Facades\Redirect::class, from aliases
  • 'Session' => Illuminate\Support\Facades\Session::class, from aliases

I also went to app/Http/Kernel.php and removed all the routeMiddleware (later I'll include JWT middleware) and I also removed session related stuffs from middleware variable.

After I did that, I started getting a Class session does not exists when trying to POST to one of my endpoints.

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(CompanyRequest $request) {
    $company = Company::create($request->all());
    return response()->json($company);
}

Anyway, my qusetion is about building a restful api in Laravel 5.1.

  • Do I need to have session related code up and running?
  • Can the session and the redirect be completely removed?
  • Are there any more features that should/could be completely removed for a REST API mode?

And most important of all, how to achieve it?



via Chebli Mohamed

How can I make a variable that can be accessable throughout my entire application routes/views in Laravel?

I make a cURL request to an API

http://ift.tt/1LXh9TW


I got back this response

    Object
    data: Object
    first_name: "Bob"
    last_name: "Jones"
    message: "Success"
    status: 200

    ___

I grab the first name and last name and concatenate them together and stored into a variable call $name.

$fn = VSE::user('first_name',$username);
$ln = VSE::user('last_name',$username);
$name = ucwords($fn.' '.$ln); // Bob Jones

I want to display this $name on my navigation.

Sending this $name variable with everyview would be a little over kill.

I'm seeking for a better way of doing this.

What should I do to make that variable accessable throughout my application routes/views ?



via Chebli Mohamed

Laravel > route, filter URL against database

I'm trying to build the new version of our site with the Laravel 5 framework.

The problem is, we have now the following site structure (and this may not be changed):

  • http://ift.tt/1LEkohE] <- dynamic
  • http://ift.tt/1PWJqM6] <- dynamic
  • http://ift.tt/1LEkmq0
  • http://ift.tt/1PWJonr
  • ....

In our database, we have a list of different product names and different categories.

I want to route the [productname] to a productController and the [categoryname] to the categoryController. But therefor, i need query our database with each request to see if the URL parameter is either a product or a category.

Any ideas to get me on right direction?

Thanks in advance!



via Chebli Mohamed

Make a global when true in Laravel 5 Model

I come from cakePHP where it is possible to have every get or list query to include a standard where "something = something" in the Model. Per function in the controller this can be ignored, but for all others this is used.

Now I am wondering how to do this in Laravel 5. I would like to add something like below code in the Model or in the Controller (but preferably in the Model):

public function __construct(Page $page) {
    $page->where('is_active', 1);
}

So that when running any query on the pages table it will only give me active pages. Except when I manually add where('is_active', 0) or something else to include all active and inactive pages.

Any help would be very appreciated



via Chebli Mohamed

InvalidStateException in AbstractProvider.php line 191 with socialite

I only get this error on my local machine when I try to login with google or fb. I'm almost 100% sure my services and session.php are set up correctly. But alas,here we are...

my services.php google settings:

'google' =>[
    'client_id'=> env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect' => "http://". env('DOMAIN'). "/login/google/callback",
],

my session

'domain'=> 'local.mysite.com'



via Chebli Mohamed

Laravel 5 - route not working

I am studying Laravel 5 now.

I have add new route as following:

Route::get('items', function () {
    // test code
});

Route::get('items/create', function () {
    echo "test";
    die();
    // test code
});

And I tried show my code on my webbrowser(http://localhost:8000/items/create). But I have got 503 error. And http://localhost:8000/items works fine. How can I fix it? Please help me.

Thanks.



via Chebli Mohamed

Perform User Authentication if condition is true

I have 2 strings

$password_api = VSE::user('password',$username); //abc
$password     = Input::get('password'); //abc


If they're matched, I want to log the user in

if ( $password == $password_api ) {

    // Not sure what to do in here ... 
    $auth = Auth::attempt();
}


This approach is just for the demo purpose.

How can I do that in Laravel 5 ?

Any hints / suggestion will be much appreciated



via Chebli Mohamed

Sub-domain routing in Laravel on shared hosting

I'm using Laravel framework version 5.1 for my web application that will be run on a shared hosting. Since I have a very limited access to this host, (e.g. I don't have a SSH access, can't create virtual hosts inside the machine etc.) I had to make some tricks to run it smoothly. Here is what I've done so far:

  1. Moved the files inside of the public/ directory to my root directory.
  2. Changed the file paths of auto load registrar in the public/index.php with the new directory.

Everything works as intended except the sub-domain routing. I defined api.myapp.com as wildcard on routes.php but when I try to visit this subdomain, Chrome gives me DNS_PROBE_FINISHED_NXDOMAIN error. Here is the code from routes.php:

Route::group([
    'domain'     => 'api.myapp.com',
    'prefix'     => 'v1',
    'middleware' => 'cors'
], function () {
    // some RESTful resource controllers
});

How can I manage to work this subdomain? What am I missing?

Thanks in advance!



via Chebli Mohamed

How to edit view of pagination in Laravel 5

I have searched several links but i didn't find any help to edit laravel pagination view. My current laravel pagination view is given below. enter image description here

How can I edit pagination look like below sample? I don't know which file to edit in laravel 5. please help me?

enter image description here



via Chebli Mohamed

Laravel return relationship object with data from pivot table

I have the following tables setup in my application:

  • user
  • job_title
  • job_title_user (pivot table)

I have setup a relationship model for job titles in the user model, like so:

/**
 * The job titles that belong to the user.
 *
 * @return Object
 */
public function jobTitles()
{
    return $this->belongsToMany('App\Models\User\JobTitle');
}

I want to be able to select multiple rows from the user table, whilst joining on the job_title_id field from the job_title_user table.

So basically i'm looking to do a select on the user table, but also select which job titles the user has assigned to them.

How can I achieve this?

Thanks!



via Chebli Mohamed

How to use andersao/l5-repository criteria feature to filter records in controllers in Laravel 5?

So I am working with andersao/l5-repository and I am trying to filter out records using the criteria feature.

So I created my own Criteria as follows:

<?php
namespace Archive\Criterias;

use Illuminate\Http\Request;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;

class OrderIdRequestCriteria implements CriteriaInterface
{
    /**
     * @var \Illuminate\Http\Request
     */
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * Apply criteria in query repository
     *
     * @param $model
     * @param RepositoryInterface $repository
     * @return mixed
     */
    public function apply($model, RepositoryInterface $repository)
    {
        $order_id = $this->request->get('order_id');

        if(!isset($order_id)) {
            return $model;
        }

        // dd($order_id);

        $model->where('order_id', '=', $order_id);

        return $model;
    }

}

And then in my controller after importing it and the repository, the index method looks like so:

public function index(Request $request)
{
    $this->documentRepo->pushCriteria(new OrderIdRequestCriteria($request));
    $documents = $this->documentRepo->paginate(20);

    return jsend()->success()
                  ->message("Resource Fetched Successfully")
                  ->data($documents->toArray())
                  ->get();
}

And yet when I pass order_id as a GET variable, I still see all the other documents which do not belong to that order. What am I doing wrong? And moreover if I uncomment the dd() in the OrderIdRequestCriteria class, I see the order_id dumped correctly which means the code is running fine.



via Chebli Mohamed

Laravel Redirect when Middleware Process checking

I am developing a laravel web application of business directory.

here is my scenario.

  1. http://localhost/genie-works/devojp/customer // user searching with keyword of business and

  2. Showing results in http://localhost/genie-works/devojp/customer/search-result?keyword=apple&searchcity=1 this page.

  3. here listing too many business data with post an enquiry feature.

  4. when clicking on the post an enquiry button page goes to http://localhost/genie-works/devojp/customer/post-enquiry/{bisinjessid}/

  5. the post enquiry page checking a middle-ware as authentication.

  6. when user not logged in the middleware redirect to login page http://localhost/genie-works/devojp/customer and showing the login form

  7. after entering login details its needs to redirect to http://localhost/genie-works/devojp/customer/post-enquiry/{bisinjessid}/ this page.

  8. but i tried the function Redirect::back its redirecting to customers page (http://localhost/genie-works/devojp/customer)

    How can i solve this issue by redirecting to my last page....

Thanks



via Chebli Mohamed

Laravel5.1 Testing JSON APIs ,Array or Object Error

My Test Code

public function test_Query()
{
    $this->post('/Controller/User_Controller/query', ['id' => $this::$id])
        ->seeJson([
            'data'   => [ 0 =>['username' =>  $this::$id.'_update']],
        ]);
}

But printf error

1) User_Test::test_Query
Unable to find JSON fragment ["data":[{"username":"1137598_update"}]] within [{"current_page":1,"data":[{"updated_at":"2015-10-29 18:57:13","username":"1137598_update"}]}].
Failed asserting that false is true.

I guess the match should not be a problem arrays and objects ? Or that I need all the attributes of data are included



via Chebli Mohamed

Laravel 5 Pusher Server Could not Find App By Key

I am having a problem that when I add task it will not triggered the event. how to I solve this ? And besides how to I solve the websocket error? I am using Pusher in order to create a realtime event.. caption of the error message of the browser



via Chebli Mohamed

can't run migrate:install in laravel5

i have laravel 5 and it works fine on browser.After then for making table in database, firstly i have create directory i.e /opt/lampp/htdocs/laravel, then run php artisan migrate:install command but i have got message shown below. How to solve this problem.

cd /opt/lampp/htdocs/lovey

/opt/lampp/htdocs/lovey$ php artisan migrate:install


  • Application In Production! *


    Do you really wish to run this command? [y/N] (yes/no) [no]:

HERE IS MY database.php file. my database name is laravel.

return [ 'fetch' => PDO::FETCH_CLASS,

'default' => env('DB_CONNECTION', 'mysql'),


'connections' => [

    'sqlite' => [
        'driver'   => 'sqlite',
        'database' => database_path('database.sqlite'),
        'prefix'   => '',
    ],

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'laravel'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

    'pgsql' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'database'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public',
    ],

    'sqlsrv' => [
        'driver'   => 'sqlsrv',
        'host'     => env('DB_HOST', 'localhost'),
        'database' => env('DB_DATABASE', 'database'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
    ],

],



'migrations' => 'migrations',



'redis' => [

    'cluster' => false,

    'default' => [
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ],

],

];



via Chebli Mohamed

Laravel 5.1 - icon in the page title

I am struggling with adding an icon into the page title. So far I have tried adding it line this :

<link rel="icon" href="{{asset('images/gcm_ico.ico')}}"

But it gets escaped in all browsers as shown here :

enter image description here

I also tried printing the link with {{ "" }}.

Has anyone done this successfully? Thanks in advance



via Chebli Mohamed

multiple database connection not working laravel

I am trying to make use of two database in application.

'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'xxxxxx'),
            'username'  => env('DB_USERNAME', 'xxxxxxx'),
            'password'  => env('DB_PASSWORD', 'xxxxxxxx'),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

        'mysql2' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'xxxxx'),
            'username'  => env('DB_USERNAME', 'xxxxxx'),
            'password'  => env('DB_PASSWORD', 'xxxxxx'),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

I have removed the connection parameters that exists in .env. Now my first connection is working properly. I can make use of the first database very fluently. But when i try to get data from the table of another database, I get SQLSTATE[HY000] [1045] Access denied for user 'xxxxxxx'@'localhost' (using password: YES). But the multiple connection is working fine in my localhost. This is how i am trying to get data from the second database

Route::post('params', function(){

    $posted = Input::get('imei');

    $user2 = DB::connection('mysql2');
    $u = $user2->table('tablename')->where('fld_imei', '=', $posted)->first();

    if (count($u) == '0'){
        echo "there are no records matching this serial number";
        die();
    }

    return view('result')
        ->with(array(
            'result'    => $u
        ));

});

How can I make this work?



via Chebli Mohamed

mercredi 28 octobre 2015

Laravel 5 Carbon format datetime

I have an array that return the following date time:

$item['created_at'] => "2015-10-28 19:18:44"

How in laravel using carbon format into this format M d Y.

Currently this method return an error

$suborder['payment_date'] = $item['created_at']->format('M d Y');

Thanks!!



via Chebli Mohamed

Laravel add commas between array elements

I just started learning laravel..

I have this "tags" array and I want to add commas between the links in my article.blade.php, like so:

Tags:
@foreach($article->tags as $tag)
    {{ $tags[] = '<a href="/tag/'. $tag->name .'">'.$tag->name .'</a>' }}
@endforeach
{!! implode(',',$tags) !!}

So it must become this:

Tags: tag1, tag2, tag3

And not this:

Tags: <a href="/tag/fun">fun</a> <a href="/tag/sports">sports</a> <a href="/tag/work">work</a> fun,sports,work

How do I do this so it looks right?



via Chebli Mohamed

NodeJS require error when running the server.js

I am having an error when running node server.js view image

I dont know why the require is an error ? I am using Laravel 5, I'm learning laravel with websocket.. please help me with this :( below is my node server.js code

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');

server.listen(8890);
io.on('connection', function (socket) {

  console.log("new client connected");
  var redisClient = redis.createClient();
  redisClient.subscribe('message');

  redisClient.on("message", function(channel, message) {
    console.log("mew message in queue "+ message + "channel");
    socket.emit(channel, message);
  });

  socket.on('disconnect', function() {
    redisClient.quit();
  });

});



via Chebli Mohamed

DOMPDF Timing out when creating large PDF

I'm using DOMPDF with Laravel 5 to generate PDFs from some of my views. It works well on everything except one where it keeps timing out. The code I am using for this view is exactly the same as what I'm using for another which works fine except this one returns more results. I've tried increasing the timeout limit but this didn't help.

Just wondering if anyone has any ideas on how to fix this? I found a few results online but they are all quite old and most of them were a bug with nested tables.

Thanks for your help.



via Chebli Mohamed

Laravel 5 where clause from another table

I have a simple code and what I want to do is to access a field from another table and put it in my where clause. This is my code:

ReportController.php

$reservations = Reservation::with('room')
-> whereBetween('reservation_from', [$from, $to])
-> where('room.type', \Request::input('type')) //what should this be
-> orderBy('created_at')
-> get();

Room.php

class Room extends Model
{
    use SoftDeletes;
    protected $table = 'rooms';

    protected $fillable = ['id', 'roomNumber', 'type', 'price', 'description'];

    public function reservations() {
        return $this->hasMany('App\Reservation', 'id', 'room_number');
    }
}

Reservation.php

class Reservation extends Model
{
    use SoftDeletes;
    protected $table = 'reservations';

    protected $fillable = ['roomNumber', 'clientId', 'reservation_from', 'reservation_to'];

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

}

Schema: enter image description here

As you can see in the ReportController.php, there is a comment saying "what should this be", that's the part that I want to fix. What I wanted to do is access the type field in the rooms table in my eloquent query.

Is there a way to do this? Thank you.



via Chebli Mohamed

How can I install laravel framework for NetBeans 7.4

I have installed Laravel and I want to use use framework annotations and code completion in the NetBeans 7.4 IDE, there is no Laravel plugin in the section "Install plug-ins". I have found a plug in for Netbeans on github but I am unsure how I install it, here is the link http://ift.tt/1MujTKL



via Chebli Mohamed

Facebook PHP SDK/Laravel 5: Check if a user has granted a certain set of permissions

I want to check that a user has authorized the following permissions; 'manage_pages', 'publish_pages', 'read_insights', for my app. In short, if they decline one or more permissions, I need to know, as all are required.

Here's my callback method once I get the user's access token. How do I verify they approved all permission requests?

Note: I'm using the SammyK Laravel Facebook SDK package.

public function handleFacebookCallback()
    {
        try {
            $token = Facebook::getAccessTokenFromRedirect();

            $user = Facebook::get('/me?fields=permissions', $token)->getGraphUser();
            $permissions = $user['permissions']->asArray();

            // permissions: 'manage_pages', 'publish_pages', 'read_insights'

            if (array_key_exists('publish', $permissions['data'][0]))
            {
                // permissions exist, proceed
            }
            else 
            {
                // user denied permission(s), redirect
            }
        }
        ....



via Chebli Mohamed

Laravel and remote mount points (sshfs)

I've mounted a drive with sshfs to use with my web app, specifically for a directory listing part of my site. (i.e listing all directories / files in a folder)

As I don't store my files where my laravel installation is, I decided to use sshfs to mount my drive where laravel scans the dir.

An ls on the mounted directory shows all my files where they're suppose to be, mounted correctly.

However with laravel it throws the error "Links are not supported, encountered link at //initrd.img"

Any input would be appreciated. Thanks!



via Chebli Mohamed

Laravel, change .env with php

I am trying to make an installer script, a little bit like wordpress installer script. I am using laravel 5.1 so i would like to write a change to my .env file so my database was set up. But i can't figure out how. Can you help me?



via Chebli Mohamed

laravel apache server issue

I am getting AWS apache following issues ERROR BadMethodCallException HELP Call to undefined method Illuminate\Database\Query\Builder::isCustomerEmailIdUnique()

this is model function

public function isCustomerEmailIdUnique($email,$customerId)
{
    $dataCustomerId = DB::table($this->table)->where('email_id',$email)->get(['customer_id']);
    // If customerId of email exist , return true. if email id not exist return false

     $data = json_decode(json_encode($dataCustomerId), true);       
     if(empty( $data) || $data['customer_id'] == $customerId ){
        return true;
    }else{
        return false;
    }
}



via Chebli Mohamed

Laravel does not want to auto-inject dependencies in Service Provider

I have a service provider:

<?php namespace App\Providers;

use Carbon\Carbon;

use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Cache\Store;

use File;

use App\Models\Translation;

class ModuleTranslationsServiceProvider extends ServiceProvider {

    protected $cache;

    public function __construct (Store $cache) {
        $this->cache = $cache;
    }

    /**
     * Load the config from the database.
     *
     * @return void
     */
    public function register()
    {
        $translations = $this->cache->remember('translations', function() {
            //Load and return translations.
        });
        $this->app->singleton('translations', function($app) use ($translations) {
            return $translations;
        });
    }

}

However I get the following error when the app is run (artisan or browser):

ErrorException]                                                                                                                                                                                                                                                                        
  Argument 1 passed to App\Providers\ModuleTranslationsServiceProvider::__construct() must be an instance of Illuminate\Contracts\Cache\Store, instance of Illuminate\Foundation\Application given, called in /home/user/projects/AppPlatform/vendor/laravel/framework/  
  src/Illuminate/Foundation/ProviderRepository.php on line 150 and defined                                                                                                                                                                                                                

Normally, Laravel auto-injects contracts via the constructor. Is this a limitation of Service Providers? Or am I doing it wrong?



via Chebli Mohamed

we failed to identify your request PHPUNIT

I have a test function -

class InstrumentTest extends TestCase {

    private $faker; 

    public function setUp() {
        $this->refreshApplication();
        $this->faker = Faker\Factory::create('en_EN');

        $user = App\User::find(2);

        $this->be($user);
    }

    /**
     * Test creating new instrument
     */
    public function testCreateNewInstrument() {
        $fakeName = $this->faker->name;

        $this->visit('/oem/instrument/create')
                ->type($fakeName, 'name')
                ->press('Create')
                ->seePageIs('/oem/instrument')
                ->see('Instrument Created Successfully!');

        # make sure that record is in the database
        $this->seeInDatabase('instrument', ['name' => $fakeName, 'company_id' => 1]);
    }
}

Each time I run "phpunit" my test die with following message in the console: "We failed to identify your request."

I am not sure on how to fix this and if this is related to the middleware?



via Chebli Mohamed

grant permission to a new role in Laravel 5

We are developing a laravel application, the application has an admin part which is only accessible to the admin users in routes file we have:

 Route::group(['middleware' => 'admin', 'prefix' => 'admin', 'namespace'
              => 'Admin'] , function() {
       Route::get('oldAdminUrl', 'oldControllwe@handle');

  }

The middleware file's handle function is like

public function handle($request, Closure $next)
{       
   if ($this->admin->guest())
    {
        //some code here
    }

    return $next($request);
}

ad the $this->Admin refers to Model called adminModel with the following attribute

 protected $table = 'admin'

Now we need to add a new url to the group of admin urls let's call it newAdminUrl it should be accessabile for both the admin users and also a new group of users let's call them editors

is it a good practice to put that url outside the admin group and assign it a new middleware let's call it editorsMiddleware in additon to admin middleware to check if the user who wants to access the newAdminUrl is either in editor group or admin group and the editors be stored in another table

 Route::group(['middleware' => ['admin','editors], 'prefix' => 'admin',      
     'namespace' => 'Admin'] , function() {
         Route::get('newAdminUrl', 'newControllwe@handle');

   }

The EditorModel which is used inside the editorMiddleware has this attribute:

     protected $table = 'editor'

The Question: what is the right or even good approach to implement it? or anyone has any better idea or suggestion?



via Chebli Mohamed

Laravel 5.1 - Javascript not loaded

My app gets the views from an ajax request by navigation. So when i click a link in my menu i retrieve all the Html that my view contains.

My javascript is included inside the main template and of course all my calls works. But once i need for example to create an animated filter gallery inside a specific view, the javascript for that view doesn't work.

This is how i've organized my app:

My template

<!-- !Doctype -->
@include('partials.doctype')

<!-- Menu -->
@include('partials.menu')

<!-- Cont -->
<section id="content-wrapper">
    @include('ajax.index')
</section>

<!-- Footer -->
@include('partials.footer')

<!-- Javascript -->
@include('partials.javascript')

</body>
</html>

My Controller (if there's an ajax call i retrieve the view without @extends() and @section(), otherwise i retrieve my full view):

// load page
public function loadPage($page){
    return (\Request::ajax()) ? view('ajax.'.$page)->render() : view('pages.'.$page);
}

My views:

For my purpose i've created 2 type of views, one extended and one with only the html i need from my ajax calls.

a) extended, it's inside "pages" folder:

@extends('main')
@section('cont')

@include('ajax.shop')

@stop

b) only html, for ajax calls, inside "ajax" folder:

<div class="content">
    <div class="container-fluid">
        <div class="row page-title-box">
            <h3 class="page-number">N. 67</h3>
            <h1 class="page-title">Shop</h1>
        </div>
    </div>
</div>

I don't understand where to put my javascript for this view if i need to implement an animated filter gallery. I've tried to put javascript inside the view but my app crashed.



via Chebli Mohamed

PHP Imap - Character not allowed in mailbox name: '.'

I try to move an email from Drafts to Sent directory.

I use the imap_mail_move method :

imap_mail_move($imapStream, $mailId, $mailBox, CP_UID);

$imapStream is the imap stream of Drafts directory

$mailBox = {imapserver}Sent

The imap_mail_move method return false

and imap_errors() return :

array:2 [
   0 => "Character not allowed in mailbox name: '.'"
   1 => "Character not allowed in mailbox name: '.'"
]

imap_list() method return :

array:41 [
   28 => "{imapserver}Sent"
   ...
   31 => "{imapserver}Drafts"
   ....
   40 => "{imapserver}INBOX"
]

Anyone has a solution ?



via Chebli Mohamed

Building a REST API in Laravel

I'm going from no-framework development to my first contact with Laravel (using version 5.1) and I'm a bit overwhelmed with the amount of stuffs to handle (migrations, seeds, hateoas, transformers, unit testing, error handling, etc).

I'd like to get some help at the return of the show method portion of it (following REST concepts). I have the following database structure:

companies -> users -> tickets -> interactions -> attachments

enter image description here

Now, when listing a specific ticket (like GET /customers/5/tickets/3), the screen needs to show all interactions for that ticket, along with all information in the ticket table (sort of like a page header) and the name of each user that created the specific interaction.

Thinking in terms of relationship, should I return all that data from the single call or should the information from the tickets table, for instance, be persisted in the front-end (from the index method call)? Even if I should persist the ticket information (header of the page), I am still left with interaction join users + N attachments for each interaction. What are the options to approach this?

I decided to open this thread because I was trying to Unit Test this call and I couldn't decide whether I should seed the database to have all the information necessary for it to work.



via Chebli Mohamed

Inserting millions of records from local to godaddy hosting

I'm trying to insert about 8 million records from an access database to a mysql database in GoDaddy.

I built a desktop java app to manage the inserts chunking 5000 records each time. I use Laravel 5.1 to manage the inserts in the server. So, basically, the java app send a request to a laravel php route, then it take care of inserting directly in my MySQL database. The first part of records inserts successfully, but than when I send another request, I get this error:

2015-10-28 10:43:57.844 java[3475:280209] Communications error: <OS_xpc_error: <error: 0x7fff7298bb90> { count = 1, contents =
    "XPCErrorDescription" => <string: 0x7fff7298bf40> { length = 22, contents = "Connection interrupted" }
}>
Got xpc error message: Connection interrupted
org.apache.http.NoHttpResponseException: api.kraftheinzapp.com:80 failed to respond



via Chebli Mohamed

Class not found error shown after every php artisan run after removing a package

Today after removing spatie/laravel-glide package via composer , after any php artisan running show bellow error message :

  [Symfony\Component\Debug\Exception\FatalErrorException]
  Class 'Spatie\Glide\GlideServiceProvider' not found

I search about this problem and call bellow statment Many times:

composer dump-auto

But the error continues to be displayed.
this is my Composer file:

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.1.*",
    "mews/captcha": "^2.1"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~4.0",
    "phpspec/phpspec": "~2.1"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php"
    ]
},
"scripts": {
    "post-install-cmd": [
        "php artisan clear-compiled",
        "php artisan optimize"
    ],
    "pre-update-cmd": [
        "php artisan clear-compiled"
    ],
    "post-update-cmd": [
        "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"
}

}

What to do?



via Chebli Mohamed

Laravel5 pagination with Jquery Ajax

I am using Laravel5 pagination. I have added some ajax code because when I click next button I don't need to refresh the page.

My issue is when I am clicking next button my page is refreshing. please help me to find this issue. My code and screen shot are given below.

In firefox firebug console showing some error "TypeError: Argument 1 of Window.getDefaultComputedStyle is not an object."

js #abilitytest: Click function for showing data in bootstrap model

$( "#abilitytest" ).click(function() {
    $.post("/abilitytest", function(response){
        $( "#abilityQuestions" ).html(response);
    });
});


$('.pagination a').on('click', function (event) {
    event.preventDefault();
    var page = $(this).attr('href');
    console.log(page);
    alert('hai');
});

enter image description here



via Chebli Mohamed

Relationship Has Many Through without firstKey

is there anyway to get result from hasManythrough relationship without the firstKey?

Right now my result is:

 return $this->hasManyThrough('App\Facility', 'App\MerchantBranchFacility', 'id,'facility_id')->select('name');

    {"facilities":[{"name":"AC","id":"13"},{"name":"Wi-Fi","id":"13"}}}

I realize that inside hasmanythrough method laravel always do this:

  return array_merge($columns, [$this->parent->getTable().'.'.$this->firstKey]);

How can i remove "id" with laravel way?



via Chebli Mohamed

Laravel 5 Carbon Unexpected data

I created new date field called start_date, and I also have two columns for created_at and updated_at which are defined as timestamp.

In my model I have following line, that should tell Laravel to treat these columns as Carbon objects.

protected $dates = ['created_at', 'updated_at', 'start_date'].

Request passes me date like this: 2015-10-28T10:37:31.337Z, and when I try to save it, I got following error:

InvalidArgumentException in Carbon.php line 414:
Unexpected data found.
Trailing data

in Carbon.php line 414
at Carbon::createFromFormat('Y-m-d H:i:s', '2015-10-28T10:37:31.337Z') in Model.php line 2925

I tried several things, including changing dateFormat on Model, changing format on property before saving model, but I keep receiving same error.

What is supposed way to handle situations like this? Can I have different types of columns handled by Carbon? Do I need to change it change format for them manually? I checked docs, but I couldn't find anything regarding that.



via Chebli Mohamed

Laravel 5: TokenMismatchException while sending post ajax on mobile

I see sometimes in logs TokenMismatchException and I noticed that this exception is thrown only for mobile users (Android, iOS) or Google Bot.

I set in meta tag csrf token and when the page is loaded I make a post ajax request. I set header in that request like that:

 $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
 });

but this token is other that the one saved on the session.

Unforunately I would be able only once to reproduce this error myself on iPhone. When I loaded the page again everything was ok (even when I deleted all browser data).

Does anyone know what is wrong?



via Chebli Mohamed

Check if Password exists

I'm using laravel 5.1. Now I want to retrieve check if a certain password is already defined in the database. Here's my database schema

/* Accounts table */

Schema::create('accounts', function (Blueprint $table) {
      $table->increments('id');
      $table->integer('pharmacist_id')->unsigned()->index();
      $table->foreign('pharmacist_id')->references('id')->on('pharmacists')->onDelete('cascade');
      $table->string('username')->unique();
      $table->string('password', 70);
      $table->string('rights');
      $table->rememberToken()
      $table->timestamps();
});

/* Pharmacists Table */

Schema::create('pharmacists', function (Blueprint $table) {
      $table->increments('id');
      $table->integer('pharmacy_id')->unsigned()->index();
      $table->foreign('pharmacy_id')->references('id')->on('pharmacies')->onDelete('cascade');
      $table->string('fname');
      $table->string('mname');
      $table->string('lname')
      $table->date('bdate');
      $table->string('email');
      $table->string('contact');
      $table->timestamps();
});

Now what I want is to check if a certain password is already defined in a certain pharmacy_id it looks something like this

$accounts = Account::whereHas('pharmacist', function($query) {
                    return $query->where('pharmacy_id', Auth::user()->id);
                })->where('password', $password)->get();

But it seems that the password is only being passed as a plain text and not encrypted. Also I tried using this method

where('password', bcrypt($password))
where('password', Hash::make($password))
where('password', Crypt::encrypt($password))

But none of this works. Any solution guys? I'm thinking of something like this and I'm not sure if this is possible

$is_valid = Auth::validate(array('pharmacist.pharmacy_id' => Auth::user()->id, 'password' => $value));

Because if I used the below code I can able to check if the user has inputted the valid password.

$is_valid = Auth::validate(array('id' => Auth::user()->id, 'password' => $value));

It's easy to check if the username and password match using the Auth::validate but the needed checking is to check if a certain pharmacist already inputted this specific password. So basically its kinda like looping in all the accounts and check if their password is the same as this specific password.

Here's what I have so far but this has some problem. If a certain pharmacy has 1000+ user then this will loop 1000x which is not optimized and not a good solution

$accounts = Account::whereHas('pharmacist', function($query) {
                    return $query->where('pharmacy_id', Auth::user()->id);
                })->get();


foreach($accounts as $account) {
    if (Hash::check($value, $account->password)) {
      // FOUND!!!
    }
}

To make it short

Pharmacy has many Pharmacists Pharmacist has one account

Now I want to check if a certain Pharmacy has an account password of "certain password" so its like I need to check all account belonging to a certain pharmacists and that pharmacy belongs to a certain pharmacy



via Chebli Mohamed

laravel with codeception unitTesting : can't check relation

I want to unittest hasMany belongsTo&more method.

environment 

  • laravel 5.0.33
  • codeception 2.0.16

example
app/User.php

public function user()
{
    return $this->hasMany('\App\Users', 'name', 'user');
}

what would be a good way to do it?



via Chebli Mohamed

mardi 27 octobre 2015

Cannot send email using Laravel 5

I wrote this code a couple of months ago. I used to be able to send email with the following configuration. But suddenly today, I am getting the following error.

Swift_TransportException in StreamBuffer.php line 265:

Connection could not be established with host localhost [Connection timed out #110]

This is the configuration from which I was able to send emails. Please help me. I am really confused?

'driver' => 'smtp',

'host' => 'localhost',

'port' => 587,

'from' => ['address' => "test@xxx.com", 'name' => "test"],

'encryption' => 'tls',

'username' => 'test@xxx.com',

'password' => '*********',

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

'pretend' => false,



via Chebli Mohamed