mardi 1 décembre 2015

Laravel parse error: syntax error, unexpected T_CLASS, expecting T_STRING

I developed a laravel application back in August this year, and it was working fine then. I am trying to run that application now, and it gives me this error:

parse error: syntax error, unexpected T_CLASS, expecting T_STRING or T_VARIABLE or '{' or '$' in D:\bkonme\artisan line 31

And line 31 is like this:

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

My PHP version is 5.6.14 and I am using XAMPP on windows platform. I have some idea of it happening because of some version conflict between laravel and PHP, but i don't know how to resolve that issue, any help?



via Chebli Mohamed

Use Form Request validation with related models

I'm using (and loving) the Laravel 5 form request validation so far. But now I'm stuck trying to validate related models.

Say I have a Car model which has many Wheel models and I'd like to validate a new car. In the CarController@store store method I'm using the following to validate the car, but this does of course not validate the wheels.

public function store(StoreCarRequest $request)
{
   // Create the car
}

What needs to be done to validate the Wheels of a Car? Can this be done with form request validation?



via Chebli Mohamed

How to return view with hashtag in Laravel 5

After saving user, I want to return to the same tab in the page with success message. How do I add hashtag in the view path or route path in laravel

if($user->save()){
            $success = "User Registered";
            return View::make('user')->with('success', $success);

When I try this, it gives me an error :-

return View::make('user#adduser')->with('success', $success);

View [user#adduser] not found

Thanks



via Chebli Mohamed

How do I build a query saying "get me all diplomas of which all steps are in this pivot table"?

I have three models in my laravel project, Step, Diploma and Pupil. This is what the relations look like:

class Pupil {
    function steps() {
        return $this->belongsToMany(Step::class);
    }

    function diplomas() {
        return $this->belongsToMany(Diploma::class);
    }
}

class Step {
    function diploma() {
        return $this->belongsTo(Diploma::class);
    }
}

class Diploma {
    function steps() {
        return $this->hasMany(Step::class);
    }
}

Now I have a form where the admin can check boxes of which steps a pupil has accomplished, which I then save by doing $pupil->steps()->sync($request['steps']);. Now what I want to do is find the diplomas of which all the steps have been accomplished and sync them too. But for some reason I can't figure out how to build that query. Is this clear? Would anyone like to help?



via Chebli Mohamed

kwebs/multiauth middleware authentication issues

I am experiencing this is logging in users. I am using the kwebs/multiauth package to handle multiple authentication. Everything works fine except when i do this and add the middleware to authenticate users like below

Route::get('ac/dashboard', ['middleware'=>'auth', 'uses' => 'Auth\AuthController@dashboard']);

It redirects user back to the login page (User is only redirected when valid credentials are provided), all users on any level is redirected to the page specified in the Authenticate file. Every login page is affected when i apply the middleware authentication above to, even when applied to just a route.

config/auth.php

<?php

return [

/*
|--------------------------------------------------------------------------
| Default Authentication Driver
|--------------------------------------------------------------------------
|
| This option controls the authentication driver that will be utilized.
| This driver manages the retrieval and authentication of the users
| attempting to get access to protected areas of your application.
|
| Supported: "database", "eloquent"
|
*/

'multi-auth' => [
    'accountmanager' => [
        'driver' => 'database',
        // 'model'  => App\AccountManager::class
        'table' => 'accountmanager'
    ],
    'user' => [
        'driver' => 'database',
        // 'model'  => App\User::class
        'table' => 'users'
    ],
    'account' => [
        'driver' => 'database',
        // 'model' => App\User::class
        'table' => 'accounts'
    ],
],

'password' => [
    'email' => 'emails.password',
    'table' => 'password_resets',
    'expire' => 60,
],

];

Auth/AuthController.php

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Requests\CustomLoginRequest;
use App\Http\Requests\AcLoginRequest;
use App\Http\Requests\UserAuthRequest;
use App\Http\Controllers\Controller;
// use App\Http\Controllers\Auth\Auth;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

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

use AuthenticatesAndRegistersUsers, ThrottlesLogins;

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

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

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

/* Custom login */
public function getAdminLogin(){
    return view('auth.login');
}

public function postAdminLogin(CustomLoginRequest $request){

    if(\Auth::user()->attempt(['email' => $request['email'], 'password' =>    $request['password'], 'active' => 1, 'approved' => 1])){
        return \Redirect::intended('cp/dashboard');
    }else{
        \Session::flash('error', 'Invalid username or password provided.');
        return \Redirect::to('auth/login');
    }
}

public function getLogout(){
    \Auth::logout();
    \Session::flash('success_message', 'You have been logged out.');
    return \Redirect::to('auth/login');
}

/* Account Manager Login */
public function getAcLogin(){
    return view('auth.account_manager_login');
}

public function postAcLogin(AcLoginRequest $request){
    if(\Auth::accountmanager()->attempt(['username' => $request->username, 'password' => $request->password, 'active' => 1, 'user_level' => 2])){
        \Session::flash('success_message', 'You have been logged in');
        return \Redirect::intended('ac/dashboard');
    } else {
        \Session::flash('error', 'Invalid username or password provided');
        return \Redirect::to('ac/login');
    }
}

public function getAcLogout(){
    // return 'loogut';
    \Auth::logout();
    \Session::flash('success_message', 'You have been logged out.');
    return \Redirect::to('ac/login');
}


}

Middleware/Authenticate.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class Authenticate
{
/**
 * The Guard implementation.
 *
 * @var Guard
 */
protected $auth;

/**
 * Create a new filter instance.
 *
 * @param  Guard  $auth
 * @return void
 */
public function __construct(Guard $auth)
{
    $this->auth = $auth;
}

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    if ($this->auth->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('auth/login');
        }
    }

    return $next($request);
}

public function logout(){
    Auth::logout();
    \Session::flash('error_message', 'You have been logged out');
    return \Redirect::to('auth/logout');
}
}



via Chebli Mohamed

Can't swap PDO instance while within transaction in codeception laravel5?

So I am working on a multi tenant multi database architecture application using Laravel 5. So basically every tenant has his own database. The authentication is using the JWTs.

The way I resolve the database connection issues is that I take the username of the tenant, and the credentials of the user. Then I first change the DB to the tenant DB using the username I got from the request and then authenticate the user against the user table in that DB. I also put a username field in the JWT for further reference when the token is used to call other routes.

So now every time the tenant user uses this token to make a request, the DB is changed by a middleware according to the username payload in the JWT and then the request is passed forward. If there is no username payload in the token, it means it is the superadmin of the system and I simply connect it to the main DB which has all the tenants information stored. The code looks something like this:

$token = JWTAuth::parseToken();
$username = $token->getPayload()->get('username');

if(! $username){
    \Config::set('database.connections.tenant.database', 'archive');
}else{
    \Config::set('database.connections.tenant.database', $username);
    \Config::set('database.default', 'tenant');
    \DB::reconnect();
}

return $next($request);

Now the requests work just fine for me but when I try to run codeception tests, it gives me this exception:

Can't swap PDO instance while within transaction.

I am guessing that the Codeception Laravel5 module is trying to run database transactions and I am not allowed to change DBs while the transaction is running. Is there a way around this?



via Chebli Mohamed

laravel 5: soft delete

I added deleted_at filed in tables and the default value is 0000-00-00 00:00:00(which is must in mysql),now using User::first() can not get the value when deleted_at = 0000-00-00 00:00:00. any idea?



via Chebli Mohamed