mercredi 27 juin 2018

Updating user data in default Laravel application

I just started using Laravel and I can't get my head around this problem... I hope more experienced people here can spot the error I'm making.

I configured a fresh laravel application and performed

php artisan make:auth

Following the instructions from https://laravel.com/docs/5.6/authentication#authentication-quickstart.

Next, I created these routes in routes/web.php:

Route::get('/user', ['as'=>"user", 'uses'=>'UserController@show']);
Route::post('/user/update', ['as' => 'user.update', 'uses' => 'UserController@update']);

This is my UserController.php:

<?php

namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
  public function show() {

    return view('user')->withUser(Auth::user());
  }
  public function update(Request $request)
    {
        $user = Auth::user();
        $user->name=$request->input('name');
        $user->email=$request->input('email');

        $user->save();
        return Redirect::route('user');
    }
}

And this is the form in my user.blade.php:

{!! Form::model($user,['action' => ['UserController@update'], 'method' => 'POST']) !!}
<tr><th colspan=2>My user data</th></tr>
  <tr>
      <td>Name</td>
      <td>{!! Form::text('name', null, ['class' => 'form-control']) !!}</td>
  </tr>
  <tr>
      <td>E-mail Address</td>
      <td>{!! Form::text('email', null, ['class' => 'form-control']) !!}</td>
  </tr>
  <tr><td colspan=2>{!! Form::submit('Submit', ['class' => 'btn btn-primary']) !!}</td></tr>

{!! Form::close() !!}

Nothing seems to happen when I click the submit button in the form... Data is not changed in the database.



via Chebli Mohamed

Formatting dynamic dates in Laravel Blade

I am working on HTML emails in which there is a date section where I want to place a placeholder as it's a dynamic data.

The HTML code where I am using dates are:

<tr>
   <td style="padding-bottom: 3%;text-align:right;">when:</td>
   <td style="padding-bottom: 3%;padding-left: 8%;">Mar 28/18 @ 7:00pm to <br> Mar 30/18 @ 7:00pm</td>
</tr>

Problem

I am wondering in place of Mar 28/18 @ 7:00pm to <br> Mar 30/18 @ 7:00pm, what placeholder do I need to format the date variables properly?



via Chebli Mohamed

Laravel 5.6 remember cookie not being set

Im using Laravel 5.6 in the Homestead environment and the standard out of the box auth.

What im looking for is to have my users login, but when they click the remember me checkbox, have it actually remember them, it seems they are only remembered for a very very short time or as long as it is they have the browser window open.

The login form has a simple checkbox for the remember me as below;

<input class="form-check-input" type="checkbox" value="" name="remember" id="remember">

In the session.php config file i have set the default SESSION_DRIVER to cookie

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

and then in the .env the same thing;

SESSION_DRIVER=cookie

In the browser when i log in and check the remember box, and have a look at the cookie storage, it doesn't set any remember cookies at all.

Has anyone else had this issue? I would love some feedback.

Thanks.



via Chebli Mohamed

Laravel5.6 - route unwanted

i have an issue on my view edit.blade of my EmployeeCOntroller.

Edit.blade.php

 <form method="PUT" action="" aria-label="" enctype="multipart/form-data">

web.php

Route::patch('/employee/{id}', 'EmployeeController@update')->name('employees.update');
Route::get('/employee/{id}', 'EmployeeController@destroy')->name('employees.delete');

EmployeeController

public function update(Request $request, $id)

i dont know why but the request to my destroy() function on my controller !!

Someone have an idee ?

Thanks all !



via Chebli Mohamed

How to use optional route parameters properly with Laravel 5.6?

I am trying to create an API with Laravel 5.6, however, it seems to me that it's not possible to use optional route parameters before/after the parameter.

I'd like to achieve the following:

Route::get('api/lists/{id?}/items', 
[
    'as'    => 'api/lists/items/get', 
    'uses'  => 'ListsController@getListItems'
]);

With the above scenario, if I'm trying to visit api/lists/1/items it shows the page. On the other hand, if I'm trying to visit api/lists/items it says that the page is not found.

What I basically want is if there's no List ID specified, Laravel should fetch all the List ID's items, otherwise it should only fetch the specific ID's items.

Q: How is it possible to the optional parameter in between the 'route words'? Is it even possible? Or is there an alternative solution to this?



via Chebli Mohamed

Laravel: How can a queued job move itself to failed_jobs on fail?

I have a queueable Job that creates a new user...

<?php

namespace App\Jobs;

...

class CreateNewUser implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /** @var array */
    public $newUserData;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $email = $this->newUserData['email'];
        if (User::whereEmail($email)->count()) {
            // TODO: Make this job fail immediately
            throw new UserWithEmailExistsException('User with email ' . $email . ' already exists');
        }

        ...
    }
}

It's a queued job because we batch process CSVs to load in many users at a time, each one requiring an entry in 2 tables plus multiple entries in roles and permissions tables. Too slow to do synchronously.

I have a check at the start of the handle() method to see if a user with the same email address has not already been created (because potentially several jobs could be queued to create users with the same email) and it throws a custom Exception if it does.

If that check fails, I don't ever want the queue worker to attempt this job again because I know it will continue to fail indefinitely, it's a waste of time to re-attempt even once more. How can I manually force this job to fail once and for all and move over to the failed jobs table?

P.S. I have found the SO answer about the fail() helper but that still does not immediately move the job from jobs to failed_jobs.



via Chebli Mohamed

FatalThrowableError when using custom guard for api authentication in laravel

I keep on getting a FatalThrowableError exception each time i try to authenticate via token or passport drivers in my custom guard (api-users) however with a session driver it works just fine. I have defined the guards as per the docs but still to no avail, I don't understand where I'm going wrong

Code

Config\Auth.php

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

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

    'api' => [ <== this is not being used as far as i know
        'driver' => 'token',
        'provider' => 'users',
    ],

    'api-users' => [  //<== I am trying to use this guard 
        'driver' => 'session', //<== session works, token or passport doesn't
        'provider' => 'api-users',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    'api-users' => [
        'driver' => 'eloquent',
        'model' => App\Models\ApiUser::class,
    ],
],

AuthController.php

class AuthController extends Controller
{
    protected function guard()
    {
        return Auth::guard('api');
    }

    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt($this->credentials($request), false);
    }

    protected function credentials(Request $request)
    {
        return $request->only('email', 'password');
    }

    public function login(Request $request)
    {
        if ($this->attemptLogin($request)) { //<== this doesn't work with token/passport driver but with a session driver
            echo 'success';
        } else {
            echo "fail";
        }
    }
}

Models\ApiUser.php

class ApiUser extends Authenticatable
{
    use SoftDeletes;
    use Notifiable;
    use HasApiTokens;

    protected $guard = 'api-users';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'mobile', 'password', 'active'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token', 'created_at', 'updated_at', 'deleted_at'];

    /**
     * Type cast the active field
     */
    protected $casts = [
        'active' => 'boolean',
    ];
}



via Chebli Mohamed