dimanche 29 janvier 2017

How to access data of one function to another in laravel

Okay the issue is something like this

I have a function in AController

public function index()
{
    $store = Store::(query)(to)(rows)->first();

    return view('store.index', compact('store'));
}

Now in the same controller I have another function

public function abc()
{
    return view('store.abc');
}

Now to this function I also want to send the compact('store') to the view abc I can just add the query again in the abc() function but that would be lazy and make performance issues. Is there a way that I can access $store object in other functions too?



via Chebli Mohamed

Laravel 5.3 / Access to different properties or columns depending on role

Working on Project with a user table with authorization. Some of the users are admins, some are just members. Depending on the respective role, the logged in user can edit all users or just the own data.

Futhermore, depending on the role, the logged in user can change all or only a few of the properties, e.g. the property "role" itself.

The best solution seems to me, to create different models on the same table, maybe with different policies (single-table-inheritance so to say).

Is this the right approach? If not, what are the alternatives?



via Chebli Mohamed

Laravel 5 - Authenticate against two tables

Before thinking this is a duplicate, this question is not the same as authenticating against different tables based on a normal user vs. admin user.

I'm somewhat new to Laravel and am having issues trying to authenticate users in the way I need it to be done. I currently have a user table and a companies table. When a user attempts to sign in, I need to check the following:

  1. The user's email and password match (fields in user table)
  2. The user is currently in an active state (field in user table)
  3. The user belongs to an active company (field in companies table)

I have seen numerous examples of authenticating with multiple tables based on whether the user is an admin or not using gaurds, but I determine if a user is an admin with the users table. I just want to check both tables with the criteria I explained above for any user logging in. I would also like to keep this the "Laravel way" as much as possible. Thank you in advance for any help provided.



via Chebli Mohamed

How can I correctly put and retrieve a GenericUser object into and from the session in this "custom user provider" Laravel login?

I am not so into PHP and Laravel and I have the following problem, I came from Java.

I am following this tutorial to implement a custom user provider:

http://ift.tt/1pfYtX4

I am using Larave 5.3 version.

I briefly expain what I need: my Laravel application is only a front end application, all the business logic, included the user authentication, is performed by a Java back end application that exposes REST web services.

Performing a call to:

http://localhost:8080/Extranet/login

and passing username and password as basic authentication I obtain a JSON response like this that represent the logged user:

{
  "userName": "Painkiller",
  "email": "painkiller@gmail.com",
  "enabled": true
}

So, in my Laravel application, I have to perform this call and then parse the previous returned JSON object to generate the authenticated object into the front end application session.

To do this I have implemented the previous tutorial (and it seems to works) implementing this custom user provider class named UserProvider that implements the Laravel IlluminateUserProvider interface:

<?php

namespace App\Authentication;

use Illuminate\Auth\GenericUser;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider as IlluminateUserProvider;
use GuzzleHttp\Client;
use function GuzzleHttp\json_encode;
use function GuzzleHttp\json_decode;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class UserProvider implements IlluminateUserProvider
{
    public function retrieveById($identifier)
    {
        // TODO: Implement retrieveById() method.
        \Log::info('retrieveById START');

        $user = \Session::get('loggedUser');

        //$user = Auth::user();

        return $user;

    }

    public function retrieveByToken($identifier, $token)
    {
        // TODO: Implement retrieveByToken() method.
        \Log::info('retrieveByToken START');
    }

    public function updateRememberToken(Authenticatable $user, $token)
    {
        // TODO: Implement updateRememberToken() method.
        \Log::info('updateRememberToken START');
    }

    public function retrieveByCredentials(array $credentials) {

        // TODO: Implement retrieveByCredentials() method.

        \Log::info('retrieveByCredentials START');
        \Log::info('INSERTED USER CREDENTIAL: '.$credentials['email'] . ' ' .$credentials['password']);

        $client = new Client(); //GuzzleHttp\Client

        $response = $client->get('http://localhost:8080/Extranet/login',
            [
                'auth' => [
                    'nobili.andrea@gmail.com',
                    'pswd'
                ]
            ]);

        $dettagliLogin = json_decode($response->getBody());

        \Log::info('response: '.(json_encode($dettagliLogin)));

        //$user = new User('Pippo', 'pippo@google.com', true);

        $attributes = array(
            'id' => 123,
            'username' => 'nobili.andrea@gmail.com',
            'password' => \Hash::make('SuperSecret'),
            'name' => 'Dummy User',
        );

        $user = new GenericUser($attributes);

        \Log::info('USER: '.(json_encode($user)));

        \Session::set('loggedUser', $user);

        return $user;


    }

    public function validateCredentials(Authenticatable $user, array $credentials)
    {
        // TODO: Implement validateCredentials() method.
        \Log::info('validateCredentials START');
        return true;
    }

}

So, doing in this way it seems to works fine but I have some doubts:

This is only a preliminary test so the returned data are mocked.

It works in this way:

1) When the user insert his credential in the login page (http://localhost:8000/login) it is called the retrieveByCredentials() method:

public function retrieveByCredentials(array $credentials) {

    // TODO: Implement retrieveByCredentials() method.

    \Log::info('retrieveByCredentials START');
    \Log::info('INSERTED USER CREDENTIAL: '.$credentials['email'] . ' ' .$credentials['password']);

    $client = new Client(); //GuzzleHttp\Client

    $response = $client->get('http://localhost:8080/Extranet/login',
        [
            'auth' => [
                'nobili.andrea@gmail.com',
                'pswd'
            ]
        ]);

    $dettagliLogin = json_decode($response->getBody());

    \Log::info('response: '.(json_encode($dettagliLogin)));

    //$user = new User('Pippo', 'pippo@google.com', true);

    $attributes = array(
        'id' => 123,
        'username' => 'nobili.andrea@gmail.com',
        'password' => \Hash::make('SuperSecret'),
        'name' => 'Dummy User',
    );

    $user = new GenericUser($attributes);

    \Log::info('USER: '.(json_encode($user)));

    \Session::set('loggedUser', $user);

    return $user;

}

that performs a web service call to obtain the user information related to this user. Then these credential are verified by the validateCredentials() method (at this time it returns true every time). Finnaly it returns a GenericUser objct containing the information of the logged user (at this time are mocked because is a test and I have not yet paresed the JSON reeturned by my web service) that is put into the session by this statment:

\Session::set('loggedUser', $user);

Then, when the verified logged user is redirected to the next page (after the success login) it seems to me that is called the retrieveById($identifier) method, this:

public function retrieveById($identifier)
{
    // TODO: Implement retrieveById() method.
    \Log::info('retrieveById START');

    $user = \Session::get('loggedUser');

    //$user = Auth::user();

    return $user;

}

that retrieve the logged user from the session so it can be used in the next view. It works fine, infact I correctly log into the next page and I can see the setted mocked Dummy User as logged user. From here also the log out function works fine.

But I am asking if put the GenericUser object into the section in the retrieveByCredentials(array $credentials) and then retrieve it into the retrieveById($identifier) is the neater solution.

Here I have posted a similar question: Can I put and retrieve the user information to and from session into a Laravel custom user provider?

And reading the obtained response it seems that the validated user is automatically putted inside the session but if I don't manually store and retrieve the user into and from the session by:

\Session::set('loggedUser', $user);

and:

$user = \Session::get('loggedUser');

in the previous 2 methods it doesn't works. Infact after the log in it come back to the login form page and not to the home page.

In the previous response it says to me about the Auth::user() method but I can't understand how exactly works and if I have to configure this SessionGuard in some way. What exactly is this SessionGuard? Have I to configure it to correctly use the session?

Anyway my original solution could be considered a good solution?



via Chebli Mohamed

Laravel autoload file variable from view

I have recently move my projects into laravel. In my projects, I have a single file which contains common variables.
My common.php file is in app/Libs/common.php

$a = array(
  'b' => 'c'
);

I also added my common file is in composer.json file.
My composer.json file

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": { 
        "App\\": "app/"
    },
    "files": [
      "app/Libs/common.php"
    ]
},

Now I want to access this variable in view.
My View file:

<?php print_r($a); ?>

It gives me following errors:

Undefined variable a (View: ...)



via Chebli Mohamed

Illegal string offset laravel 5

Below is my query which fetches name of user

$userName4 = User::where('_id', '=', $userId4)->first()->name;

Output

CHANDRA PRAKASH SHARMA

Then

$data[$flevel][$userName2[0]['name']][$userName3[0]['name']][$userName4] = $eachSetData4[$level[2]];
// $data[South][Sajeev MT][Jayasheela G][CHANDRA PRAKASH SHARMA] = '1213we23121ws';

But I am getting following error,

Illegal string offset 'CHANDRA PRAKASH SHARMA'

Please help me to resolve this issue.



via Chebli Mohamed

Laravel 5.4 installation error.

I am setting up my project using laravel installer command,

laravel new blog

But it returns the following errors.

Generating autoload files

php -r "file_exists('.env') || copy('.env.example', '.env');" Class Illuminate\Foundation\ComposerScripts is not autoloadable, can not call post-install-cmd script php artisan optimize PHP Warning: require(/var/www/blog/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php): failed to open stream: No such file or directory in /var/www/blog/vendor/composer/autoload_real.php on line 55 PHP Fatal error: require(): Failed opening required '/var/www/blog/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php' (include_path='.:/usr/share/php') in /var/www/blog/vendor/composer/autoload_real.php on line 55 Script php artisan optimize handling the post-install-cmd event returned with an error

[RuntimeException]
Error Output: PHP Warning: require(/var/www/blog/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php): failed to open stream: No
such file or directory in /var/www/blog/vendor/composer/autoload_real.php on line 55
PHP Fatal error: require(): Failed opening required '/var/www/blog/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php' (include
_path='.:/usr/share/php') in /var/www/blog/vendor/composer/autoload_real.php on line 55

run-script [--timeout TIMEOUT] [--dev] [--no-dev] [-l|--list] [--] [] []...

Application ready! Build something amazing.

My development environment setup:-

Ubuntu 16.04, 64 bit
Composer version 1.0.2
Laravel Installer 1.3.3
PHP 7.0.8-0ubuntu0.16.04.3



via Chebli Mohamed