2

So I am building a checkout functionality. If the user is a guest he could use his credentials to make a new registration with the order he makes. I have used the auth scaffold Laravel provides with the command php artisan make:auth. I have an OrdersController and the AuthController that comes with the framework. How can I register a new user within my OrdersController? Here is my code: checkout.blade.php:

<li class="col-md-12 col-sm-12">
    <h4>Register</h4>

    <input id="create-act" type="checkbox" class="input-chkbox" name="register">
    <label for="create-act">Create user account?</label>
</li>
<li class="col-md-12 col-sm-12 create-account">

    <label for="password">Password<em>*</em></label>
    <input required type="text" class="input-text" id="password"
           name="password">
</li>
<li class="col-md-12 col-sm-12 create-account">
    <label for="password_confirmation">Confirm Password<em>*</em></label>
    <input required type="text" class="input-text"
           id="password_confirmation"
           name="password_confirmation">
</li>

OrdersController inside addOrder method:

if(isset($_POST['register'])) {
 $this->validate($request, [
        'password' => 'required|password',
        'confirm_password' => 'required|'
    ]);
}

I want to register the new user inside this if. How can I do that?

Edit: Here is my protected function create inside my AuthController.

protected function create(array $data)
{
    $confirmationCode = str_random(30);

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'confirmation_code' => $confirmationCode
    ]);

    $user->roles()->attach(Role::where('name', 'Customer')->first());
    $cart = new Cart();
    $cart->user_id = $user->id;
    $cart->save();
    if(Session::has('cartItems')) {
        foreach (Session::get('cartItems') as $sessionCartItem) {
            $cartItem = new CartItem();
            $cartItem->product_id = $sessionCartItem['product']->id;
            $cartItem->cart_id = $cart->id;
            $cartItem->size = $sessionCartItem['size'];
            $cartItem->quantity = $sessionCartItem['quantity'];
            $cartItem->save();
        }
    }

    Session::flush();
    $cart->save();

    $email = $user['email'];
    $name = $user['name'];

    Mail::send('auth.emails.user-confirmation', ['name' => $name, 'confirmation_code' => $user['confirmation_code']], function ($message) use ($email, $name) {
        $message->from('[email protected]', 'Name Family')->to($email, $name)->subject('Confirm email');
    });

    return $user;
}
5
  • Why re-implement this? Why not use the existing controller which already registers users and just change the redirect to your checkout? Commented Jun 14, 2016 at 14:05
  • Because I need to be able to register users inside my register page as well. Commented Jun 14, 2016 at 14:07
  • You don't have to permanently change the default redirect. Only if the reg request is coming from a checkout. Commented Jun 14, 2016 at 14:10
  • @apokryfos My register method needs a Request $request to work. I get the request for my addOrder method and I need to pass that $request to the redirect. How can I do that? Commented Jun 14, 2016 at 14:52
  • Actually since you've updated the question, it's probably far easier to make the create function in the AuthController public static and call it from the OrderController. Of course it's even better if you move this to a library instead of having it as a controller method (since it is more business logic than it is controller logic). Commented Jun 14, 2016 at 14:56

4 Answers 4

2

Normally, you can easily create user with the request:

$user = User::create($request->all());

Make sur that the $request variable matches the columns of users table.

EDIT: To call a function from another controller:

class OrdersController extends AuthController
{
    ...
    $this->create(...);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I have updated my question. Check my create method inside my AuthController. There I attach roles and send a confirmation email. How can I access that method from my OrdersController, rather than using User::create($data)?
@Codearts just extends the AuthController and you can call the function create. See my edit.
2

After you validation succeeds Fetch out all the data from $request that you need for you user table, use the User model to insert a column,

you can use

$user=User::create($dataObject);

or you can use

$user=User::insert([
'username'=>$request->username,
'password'=>Hash::make($request->password)
]);

Than you can use the Auth Guard method to login the user

Auth::login($user);
return;

Edit : Create a library function and use it where ever you want

<?php

namespace App\Lib\User;

class Creator
{
    public function create(Request $request)
    {
       // do what you want
      // return what you want
    }
}

Than use this function in order controller or auth controller

use App\Lib\User\Creator;

 public function __construct(Creator $creator) {
        $this->creator=$creator;
    }
 public function register(){
  $user=$this->creator->create($data);
 }

2 Comments

I have updated my question. Check my create method inside my AuthController. There I attach roles and send a confirmation email. How can I access that method from my OrdersController, rather than using User::create($data)?
You can not use a protected function of a class in to other unless you extend it, instead of using the same function of controller create a seperate class in a different folder , use that class in both order controller and auth controller The way i have done in my application is that i have a librar folder inside the app folder in that i have user folder and in that i have to files creator.php and updator.php creator.php consists of a class and a function to create a user, i just use this class in any controller and call this function
1

The AuthController does a simple User::create($data); after the validation is done. Optionally you could do Auth::guard()->login($user); which will automatically login the newly created user.

1 Comment

I have updated my question. Check my create method inside my AuthController. There I attach roles and send a confirmation email. How can I access that method from my OrdersController, rather than using User::create($data)?
1

I didn't want my OrdersController to extend my AuthController, was to lazy to extract the authentication logic into a library and just redirecting if the register checkbox was checked didn't work. I just decided to duplicate part of my registration logic inside my OrdersController. It is not good practice for sure, but it is a workaround until I extract the login into a library. Here is the code:

if (isset($_POST['register'])) {
    $this->validate($request, [
       'password' => 'required|min:6|confirmed',
       'password_confirmation' => 'required'
    ]);

    $user = User::create([
        'name' => $request['name'],
        'email' => $request['email'],
        'password' => bcrypt($request['password']),
        'phone_number' => $request['phone']
    ]); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.