简体   繁体   中英

Laravel 5.1 Eloquent insert into another table on register

I'm trying to modify my register (the Laravel 5.1 build-in register) so I can insert a record into another table.

My register:

    <?php

namespace Cussion\Http\Controllers\Auth;

use Cussion\User;
use Request;
use Validator;
use Redirect;
use Cussion\Http\Controllers\Controller;
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;

    private $redirectTo = '/dashboard';
    private $maxLoginAttempts = 3;

    /**
     * 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)
    {

        $messages = [
            'firstname.required' => '<script>toastr["error"]("Het invullen van het veld is vereist!.", "Registreren mislukt")</script>',
            'firstname.max' => '<script>toastr["error"]("U mag maar maximaal :max karakters ingeven.", "Registreren mislukt")</script>',
            'lastname.required' => '<script>toastr["error"]("Het invullen van het veld is vereist!.", "Registreren mislukt")</script>',
            'lastname.max' => '<script>toastr["error"]("U mag maar maximaal :max karakters ingeven.", "Registreren mislukt")</script>',
            'email.required' => '<script>toastr["error"]("Het invullen van het veld is vereist!", "Registreren mislukt")</script>',
            'email.email' => '<script>toastr["error"]("U moet een bestaand e-mail adres opgeven!", "Registreren mislukt")</script>',
            'email.max' => '<script>toastr["error"]("U mag maar maximaal :max karakters ingeven.", "Registreren mislukt")</script>',
            'email.unique' => '<script>toastr["error"]("Het opgegeven e-mail adres bestaat al.", "Registreren mislukt")</script>',
            'password.require' => '<script>toastr["error"]("Het invullen van het veld is vereist!", "Registreren mislukt")</script>',
            'password.min' => '<script>toastr["error"]("U moet minimaal :min karakters gebruiken voor uw wachtwoord.", "Registreren mislukt")</script>',
            'password2.require' => '<script>toastr["error"]("Het invullen van het veld is vereist!", "Registreren mislukt")</script>',
            'password2.same' => '<script>toastr["error"]("De twee wachtwoorden komen niet overeen.", "Registreren mislukt")</script>',
        ];

        $rules = [
            'firstname' => 'required|max:255',
            'lastname' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:4',
            'password2' => 'required|same:password',
            ];

        return Validator::make($data, $rules, $messages);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {

        if (User::where('slug', '=', strtolower($data['firstname']).'.'.strtolower($data['lastname']))->exists()) {

            return User::create([
                'firstname' => strtolower(htmlspecialchars($data['firstname'])),
                'lastname' => strtolower(htmlspecialchars($data['lastname'])),
                'slug' => strtolower(htmlspecialchars($data['firstname'])).'.'.strtolower(htmlspecialchars($data['lastname'])).'.'.time(),
                'email' => strtolower($data['email']),
                'password' => bcrypt($data['password']),
                'ip_reg' => Request::ip(),
            ]);

        }else{

            $user = new User;
            $user->firstname = strtolower($data['firstname']);
            $user->lastname = strtolower($data['lastname']);
            $user->slug = strtolower($data['firstname']).'.'.strtolower($data['lastname']);
            $user->email = strtolower($data['email']);
            $user->password = bcrypt($data['password']);
            $user->ip_reg = Request::ip();
            $user->userImages()->create(['image' => 'empty-avatar.png']);
            $user->save();

            Session::flash('success', '<script>toastr["success"]("Uw profiel is nu up to date.", "Profiel succesvol bijgewerkt")</script>');
            return Redirect::to('dashboard');
        }
    }

}

My Models:

<?php

namespace Cussion;

use Illuminate\Database\Eloquent\Model;

class UserImage extends Model
{
    protected $table = 'users_images';

    protected $fillable = ['user_id','image'];
}

The User.php

<?php

namespace Cussion;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Bican\Roles\Traits\HasRoleAndPermission;
use Bican\Roles\Contracts\HasRoleAndPermission as HasRoleAndPermissionContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract, HasRoleAndPermissionContract
{
    use Authenticatable, CanResetPassword, HasRoleAndPermission;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['firstname', 'lastname', 'email', 'password', 'ip_reg', 'slug'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];


    public static function userImages()
    {
        return $this->hasMany('Cussion\UserImage');
        //Laravel automatically snake case your model 
        //so it will assume the foreign key is named user_id
    }

}

In my controller I have 2 seperate methods to store. I don't know wich one to use... Please, help me out.

So here I check if a user slug exist and if so, it needs to add the time(); I acctually want to have added 1 if it is the first and 2 if second and so on. Just like you have on facebook, so maybe if someone can fix that too, would be great.

I want to insert a new record in users_images with the user_id of the just registered user.

This is what that table has of values:

id, user_id, image, created_at, updated_at

I acctually just want to have the user_id and timestamps filled in, since the rest will go automatic.

How can I do this using Laravel 5.1 ?

Create a model for users_images(btw is this a pivot or just a one to many relationship?)

namespace App;
use Illuminate\Database\Eloquent\Model;


class UserImage extends model{
      protected $table='users_images';
      protected $fillable = ['user_id','image'];

}

in your user model add

public function userImages()
{
    return $this->hasMany('App\UserImage');
    //Laravel automatically snake case your model 
    //so it will assume the foreign key is named user_id
}

now you can use the relationship to create new models like so :

$user->userImages()->create(['image'=>whateves]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM