Автоматическая подача полей при регистрации в Laravel - PullRequest
0 голосов
/ 15 мая 2019

Добро пожаловать. Я изучал Ларавелу несколько дней и остановился на регистрации. У меня есть миграция:

Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name', 120);
        $table->string('surname', 120);
        $table->string('email', 120)->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->bigInteger('counter')->default(0);
        $table->string('url_address', 160);
        $table->string('ip', 25);
        $table->dateTime('date_of_registration');
        $table->bigInteger('company_id')->unsigned();
        $table->boolean('isCompany')->default(0);
        $table->boolean('isMailing')->default(0);
        $table->text('note');
        $table->string('nip1', 12);
        $table->string('business1', 120);
        $table->string('phone1', 60);
        $table->string('street1', 150);
        $table->string('number1', 8);
        $table->string('postal_code1', 12);
        $table->string('city1', 100);
        $table->bigInteger('country_id1')->default(0);
        $table->bigInteger('provincial_id1')->default(0);
        $table->string('nip2', 12);
        $table->string('business2', 120);
        $table->string('phone2', 60);
        $table->string('street2', 150);
        $table->string('number2', 8);
        $table->string('postal_code2', 12);
        $table->string('city2', 100);
        $table->bigInteger('country_id2')->default(0);
        $table->bigInteger('provincial_id2')->default(0);
        $table->string('nip3', 12);
        $table->string('business3', 120);
        $table->string('phone3', 60);
        $table->string('street3', 150);
        $table->string('number3', 8);
        $table->string('postal_code3', 12);
        $table->string('city3', 100);
        $table->bigInteger('country_id3')->default(0);
        $table->bigInteger('provincial_id3')->default(0);
        $table->decimal('cash', 9, 2)->default(0);
        $table->rememberToken();
        $table->timestamps();
        $table->engine = "InnoDB";
    });

и функции:

function generateSeoUrl(string $string): string
{
    $string = preg_replace("/ +/", "-", trim($string));
    $string = mb_strtolower(preg_replace('/[^A-Za-z0-9-]+/', '', $string), 'UTF-8');
    return $string;
}

В приведенной выше таблице используется авторизация по умолчанию Laravel (я использую Laravel 5.8).

Как добавить при регистрации:

- ip - IP address of the user who registered
- date_of_registration - current date
- url_address - here I would like to save the generatedSeoUrl result ($ email)

Пожалуйста, помогите. Я сидел здесь часами и не знаю, как с этим справиться: (

Ответы [ 3 ]

0 голосов
/ 15 мая 2019

Шаг: 1:

Добавить дополнительные поля в таблицу миграции пользователей

Вы уже сделали

Шаг: 2

Добавьте файлы к заполняемой модели User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

/**
 * @property integer $id
 * @property string $name
 * @property string $surname
 * @property string $email
 * @property string $email_verified_at
 * @property string $password
 * @property integer $counter
 * @property string $url_address
 * @property string $ip
 * @property string $date_of_registration
 * @property integer $company_id
 * @property boolean $isCompany
 * @property boolean $isMailing
 * @property string $note
 * @property string $nip1
 * @property string $business1
 * @property string $phone1
 * @property string $street1
 * @property string $number1
 * @property string $postal_code1
 * @property string $city1
 * @property integer $country_id1
 * @property integer $provincial_id1
 * @property string $nip2
 * @property string $business2
 * @property string $phone2
 * @property string $street2
 * @property string $number2
 * @property string $postal_code2
 * @property string $city2
 * @property integer $country_id2
 * @property integer $provincial_id2
 * @property string $nip3
 * @property string $business3
 * @property string $phone3
 * @property string $street3
 * @property string $number3
 * @property string $postal_code3
 * @property string $city3
 * @property integer $country_id3
 * @property integer $provincial_id3
 * @property float $cash
 * @property string $remember_token
 * @property string $created_at
 * @property string $updated_at
 */
class User extends Authenticatable
{
    use Notifiable;

    /**
     * @var array
     */
    protected $fillable = ['name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address', 'ip', 'date_of_registration', 'company_id', 'isCompany', 'isMailing', 'note', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'remember_token', 'created_at', 'updated_at'];

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

}

Шаг: 3

Добавить поля в регистрационную форму можно в projectname\resources\views\auth\register.blade.php

Добавить необходимые поля в форму

Шаг: 4

Теперь логическая часть

Откройте файл project\app\Http\Controllers\Auth\RegisterController.php

Теперь вы найдете валидатор и метод создания

Добавьте ваш метод к RegisterController.php

function generateSeoUrl(string $string): string
    {
        $string = preg_replace("/ +/", "-", trim($string));
        $string = mb_strtolower(preg_replace('/[^A-Za-z0-9-]+/', '', $string), 'UTF-8');
        return $string;
    }

Добавьте логику проверки в validator метод

/**
     * 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', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

Теперь нам нужно вручную добавить несколько файлов при сохранении

/**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        $newArray = [
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'ip' => RequestFacade::ip(),
            'date_of_registration' => now(),
            'url_address' => $this->generateSeoUrl($data['email']),
        ];
        return User::create($newArray);
    }

Наконец, Ваш RegisterController будет выглядеть как

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request as HttpRequest;
use Illuminate\Support\Facades\Request as RequestFacade;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * 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', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        $newArray = [
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'ip' => RequestFacade::ip(),
            'date_of_registration' => now(),
            'url_address' => $this->generateSeoUrl($data['email']),
        ];
        return User::create($newArray);
    }

    function generateSeoUrl(string $string): string
    {
        $string = preg_replace("/ +/", "-", trim($string));
        $string = mb_strtolower(preg_replace('/[^A-Za-z0-9-]+/', '', $string), 'UTF-8');
        return $string;
    }
}

Пожалуйста, прокомментируйте, если есть какие-либо проблемы

0 голосов
/ 15 мая 2019

@ торговец

Я буду предполагать, что вы используете контроллер регистрации laravel по умолчанию в "App \ Http \ Controllers \ Auth \ RegisterController"

Итак, в вашем RegisterController есть защищенный метод создания, который принимает массив данных (данные из отправленной формы)

Чтобы получить IP-адрес, laravel предоставил метод для этого в своем объекте запроса. Итак, у вас есть $ip = Request::ip()

Что касается даты, вы можете использовать углерод, который поставляется по умолчанию $date = \Carbon\Carbon::now()

Что касается получения seoUrl, вы делаете эту функцию закрытой функцией в классе RegisterController и вызываете ее, передавая нужную вам строку (возможно, полное имя).

Итак, по сути, ваш метод создания будет выглядеть так

protected function create(array $data)
{
    return User::create([
    'name' => $data['name'],
    'email' => $data['email'], 
    'seoUrl' => $this->generateSeoUrl($data['name']),
    'ip' => Request::ip(),
    'data_of_registration' => \Carbon\Carbon::now(),
    ... /*Other form fields continue*/
    'password' => Hash::make($data['password']),

    ]);
}
0 голосов
/ 15 мая 2019

В App\Http\Controllers\Auth\RegisterController.php обновите функцию create() и поместите туда все свои дополнительные поля.

Кстати, вам не нужно date_of_registration, так как поле created_at уже управляется Laravel.

Также вместо generateSeoUrl вы можете использовать функцию Str :: slug от Laravel.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...