Automatic filing of fields during registration in Laravel - php

Welcome.
I have been learning Laravela for a few days and stopped at registration.
I have migration:
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";
});
and functions:
function generateSeoUrl(string $string): string
{
$string = preg_replace("/ +/", "-", trim($string));
$string = mb_strtolower(preg_replace('/[^A-Za-z0-9-]+/', '', $string), 'UTF-8');
return $string;
}
The above table uses Laravel's default authorization (I use Laravel 5.8).
How can I add during registration:
- 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)
Please help. I've been sitting here for hours and I do not know how to deal with it :(

Step: 1 :
Add the extra Fileds to the users table migration
You have done already
Step: 2
Add the fileds to the fillable model of 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',
];
}
Step:3
Add the fileds in the registration form can be found in projectname\resources\views\auth\register.blade.php
Add the required filed to the form
Step: 4
Now the Logic part
Open the file project\app\Http\Controllers\Auth\RegisterController.php
Now You will find the validator and create method
Add your method to the 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;
}
Add your validation logic in validator method
/**
* 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'],
]);
}
Now we need to manually add some fileds while storing
/**
* 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);
}
Finally Your RegisterController will look like
<?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;
}
}
Please do comment if there is any issue

In App\Http\Controllers\Auth\RegisterController.php update your create() function and put all your extra fields there.
By the way, you don't need date_of_registration as the created_at field is already managed by Laravel.
Also, instead of your generateSeoUrl you can use Str::slug function from Laravel.

#trafficker
I will be assuming that you are using the default laravel registration controller in "App\Http\Controllers\Auth\RegisterController"
So in your RegisterController, there is a protected create method which accepts an array of data (data from the form submitted)
To get the ip address, laravel has provided a method for that on its Request Object
So you have $ip = Request::ip()
As for the date, you can use carbon which comes by default $date = \Carbon\Carbon::now()
As for getting the seoUrl, you make that function a private function in the RegisterController class and call it passing the string you want, (maybe the full name).
So In effect, your create method will look like this
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']),
]);
}

Related

How to insert authenticated user id in database without using it in the fillable array

I am a beginner in Laravel and following a Laravel tutorial where the instructor is using Laravel 7 while I have Laravel 8 installed. He said we do not want to use user_id in the $fillable array because of security reasons so while creating a new record he used
auth()->user()->stories()->create([
'title' => $request->title,
'body' => $request->body,
'type' => $request->type,
'status' => $request->status,
]);
instead of
Story::create([
'title' => $request->title,
'body' => $request->body,
'type' => $request->type,
'status' => $request->status,
'user_id' =>auth()->id()
]);
but this code is not working for me with the error "Undefined method stories".
Here is my StoriesController
<?php
namespace App\Http\Controllers;
use App\Models\Story;
use Illuminate\Http\Request;
class StoriesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$stories = Story::where('user_id',auth()->id())->orderBy('id','desc')->paginate(4);
return view('stories.index')->with('stories',$stories);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('stories.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
auth()->user()->stories()->create([
'title' => $request->title,
'body' => $request->body,
'type' => $request->type,
'status' => $request->status,
'user_id' =>auth()->id()
]);
return redirect('/stories');
}
/**
* Display the specified resource.
*
* #param \App\Models\Story $story
* #return \Illuminate\Http\Response
*/
public function show(Story $story)
{
return view('stories.show',[
'story' => $story
]);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Story $story
* #return \Illuminate\Http\Response
*/
public function edit(Story $story)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Story $story
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Story $story)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Story $story
* #return \Illuminate\Http\Response
*/
public function destroy(Story $story)
{
//
}
}
Here is the Story Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Story extends Model
{
use HasFactory;
protected $fillable = ['title','body','type','status'];
public function user(){
return $this->belongsTo(user::class);
}
}
and here is the User Model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function stories(){
return $this->hasMany(Story::class);
}
}
I would really appreciate any assistance provided . Thank You

YII2 - Save user ID to work with it on other pages

I'm building a questionnaire site.
On this site the user enters his email to receive the result of his questionnaire. So this site has no authentication.
How do I store the user's email to the end of the questionnaire?
It is my User model:
<?php
namespace common\models;
use Yii;
use \yii\db\ActiveRecord;
// use yii\web\IdentityInterface;
/**
* This is the model class for table "user".
*
* #property int $id
* #property string $email
* #property string $name
* #property string $family
* #property string $major
* #property string $univercity
* #property int $education
* #property int $gender
* #property int $age
* #property int $income
* #property int $get_result
* #property int $created_at
*/
class User extends ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'user';
}
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
// TimestampBehavior::className(),
];
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['email', 'created_at'], 'required'],
[['education', 'gender', 'age', 'income', 'get_result', 'created_at'], 'integer'],
[['email', 'name', 'family', 'major', 'univercity'], 'string', 'max' => 255],
[['email'], 'unique'],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'email' => 'Email',
'name' => 'Name',
'family' => 'Family',
'major' => 'Major',
'univercity' => 'Univercity',
'education' => 'Education',
'gender' => 'Gender',
'age' => 'Age',
'income' => 'Income',
'get_result' => 'Get Result',
'created_at' => 'Created At',
];
}
}
There are many ways of achieving that, it mostly depends on your logic under the hood.
One of the easiest is to use session.
First store the email in session:
\Yii::$app->session->set('questionnaire-email', $usersEmail);
Then, when you want to use it:
$email = \Yii::$app->session->get('questionnaire-email');

Object of class app\models\Users could not be converted to string in yii

I created a two models:
Login.php and Users.php
Where the Users.php I will get the data from the Users table.
Then, I have created a LoginController.php which is my controller
Then I ran my app I had received this error:
Object of class app\models\Users could not be converted to string
These are my codes:
Login.php:
<code>`<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "users".
*
* #property string $user_id
* #property string $first_name
* #property string $last_name
* #property string $position
* #property string $username
* #property string $password
* #property string $dept_id
*/
class Login extends \yii\db\ActiveRecord
{
public $post;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'users';
}
/**
* #inheritdoc
*/
public static function getUsers()
{
$post = Users::find()
->where(['user_id' => 1])
->one();
return $post;
}
}`</code>
Users.php
`
namespace app\models;
use Yii;
/**
* This is the model class for table "users".
*
* #property string $user_id
* #property string $first_name
* #property string $last_name
* #property string $position
* #property string $username
* #property string $password
* #property string $dept_id
*/
class Users extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'users';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_id', 'first_name', 'last_name', 'position', 'username', 'password', 'dept_id'], 'required'],
[['user_id', 'dept_id'], 'string', 'max' => 10],
[['first_name', 'last_name'], 'string', 'max' => 30],
[['position', 'username', 'password'], 'string', 'max' => 25],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'user_id' => 'User ID',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'position' => 'Position',
'username' => 'Username',
'password' => 'Password',
'dept_id' => 'Dept ID',
];
}
}
`</code>
LoginController.php
<?php
namespace app\controllers;
use app\models\Login;
class LoginController extends \yii\web\Controller
{
public function actionIndex()
{
// $this->layout = 'loginLayout';
// $this->render('index');
$details = new Login();
$model = $details->getUsers();
$this->render('index',array('model'=>$model));
}
}
I am new in YII I just started studying these
any answers will help thanks
In Login class You declared a static function getUsers(), then You try to use it as non-static in LoginController.php:11
$model = $details->getUsers();
Should be:
$model = Login::getUsers();
And it's only answer we can provide here - not contain a solution to Your problem - please attach view code so we will have a full preview.

Getting unknown property Exception in yii2

here I have a model in yii2
<?php
namespace app\models;
/**
* This is the model class for table "car_ad".
*
* #property integer $id
* #property integer $brand_id
* #property integer $sub_brand_id
* #property integer $sell_type
* #property integer $year
* #property integer $the_function
* #property integer $fuel_type_id
* #property integer $gearbox
* #property integer $sell_mode
* #property integer $real_price
* #property integer $prepayment
* #property integer $installment_price
* #property integer $no_installments
* #property integer $delivery_time_id
* #property integer $installments_period
* #property integer $body_status_id
* #property integer $body_color_id
* #property integer $inside_color_id
* #property integer $number_type
* #property string $description
* #property integer $ad_type_id
* #property integer $provice_id
* #property integer $city_id
* #property string $address
* #property string $lang
* #property string $lat
* #property string $creation_date
* #property integer $user_id
*/
class CarAd extends \yii\db\ActiveRecord
{
public $imageFiles;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'car_ad';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['brand_id', 'sub_brand_id', 'sell_type', 'year', 'used_value', 'fuel_type_id', 'gearbox', 'body_status_id', 'body_color_id', 'number_type', 'ad_type_id', 'provice_id', 'city_id', 'address', 'lang', 'lat', 'creation_date', 'user_id'], 'required'],
[['brand_id', 'sub_brand_id', 'sell_type', 'year', 'fuel_type_id', 'used_value ', 'gearbox', 'sell_mode', 'real_price', 'prepayment', 'installment_price', 'no_installments', 'delivery_time_id', 'installments_period', 'body_status_id', 'body_color_id', 'inside_color_id', 'number_type', 'ad_type_id', 'provice_id', 'city_id', 'creation_date', 'user_id'], 'integer'],
[['description'], 'string'],
[['address', 'lang', 'lat'], 'string', 'max' => 512],
[['imageFiles'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg', 'maxFiles' => 10],
];
}
public function upload()
{
foreach ($this->imageFiles as $file) {
$image = New CarAdImage();
$image->image = $file->baseName . '.' . $file->extension;
$image->car_ad_id = $this->id;
$image->save();
$file->saveAs('img/car_ad/' . $file->baseName . '.' . $file->extension);
}
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'شناسه', 'brand_id' => 'برند', 'sub_brand_id' => 'مدل','sell_type' => 'فروش به صورت',
'year' => 'سال','used_value' => 'کارکرد','fuel_type_id' => 'سیستم سوخت','gearbox' => 'گیربکس',
'sell_mode' => 'نوع فروش','real_price' => 'قیمت نقدی','prepayment' => 'پیش پرداخت','installment_price' => 'مبلغ هر قسط','no_installments' => 'تعداد اقساط','delivery_time_id' => 'موعد تحویل',
'installments_period' => 'دوره پرداخت',
'body_status_id' => 'وضعیت بدنه',
'body_color_id' => 'رنگ بدنه',
'inside_color_id' => 'رنگ داخل',
'number_type' => 'نوع پلاک',
'description' => 'توضیحات اضافی',
'ad_type_id' => 'نوع آگهی',
'provice_id' => 'استان',
'city_id' => 'شهرستان',
'address' => 'آدرس',
'lang' => 'طول جغرافیایی',
'lat' => 'عرض جغرافیایی',
'creation_date' => 'تاریخ ایجاد',
'user_id' => 'کاربر ایجاد کننده',
'imageFiles' => 'تصاویر آگهی'
];
}
}
when I want to submit the form I face with this error.
Getting unknown property: app\models\CarAd::used_value
but as you see I have this field in my fields.
My table name is car_ad.
what is the problem with my code?
Because this field is not present in the #property comment I guess you have added it after the model has been generated. If you have got the DB schema cached new fields are not fetched until cache is updated. Try to remove the cache for DB.
Yii::$app->cache->flush(); worked for me too

PHP Compile Error while creating Views and Controller using Gii in YII2

I have created Review model for the table. after that while creating views and controllers for the same table it shows PHP Compile error.
PHP Compile Error – yii\base\ErrorException
Declaration of app\models\Review::getRelation() must be compatible with yii\db\ActiveRecordInterface::getRelation($name, $throwException = true)
Here is the full error page
http://pastebin.com/kf8RFun8 .
I have created rest of the MVCs for my tables. I get error only for this.
My Model Class
app\models\Review
Search Model Class
app\models\ReviewSearch
Controller Class
app\controllers\ReviewController
Note: while creating this same in Yii2-Advanced It shows Error (#64) Internal Server Error
Review Model:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "review".
*
* #property string $id
* #property string $title
* #property string $reviewer_id
* #property string $timestamp
* #property string $description
* #property string $organization_id
* #property integer $rating
* #property string $relation_id
* #property integer $send_msg
* #property string $org_contact_email
* #property string $org_contact_msg
*
* #property Answer[] $answers
* #property Reviewer $reviewer
* #property Organization $organization
* #property Relation $relation
*/
class Review extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'review';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['title', 'reviewer_id', 'organization_id', 'rating', 'relation_id'], 'required'],
[['reviewer_id', 'organization_id', 'rating', 'relation_id', 'send_msg'], 'integer'],
[['timestamp'], 'safe'],
[['title'], 'string', 'max' => 45],
[['description'], 'string', 'max' => 2000],
[['org_contact_email'], 'string', 'max' => 60],
[['org_contact_msg'], 'string', 'max' => 1000]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Title',
'reviewer_id' => 'Reviewer ID',
'timestamp' => 'Timestamp',
'description' => 'Description',
'organization_id' => 'Organization ID',
'rating' => 'Rating',
'relation_id' => 'Relation ID',
'send_msg' => 'Send Msg',
'org_contact_email' => 'Org Contact Email',
'org_contact_msg' => 'Org Contact Msg',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAnswers()
{
return $this->hasMany(Answer::className(), ['review_id' => 'id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getReviewer()
{
return $this->hasOne(Reviewer::className(), ['id' => 'reviewer_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getOrganization()
{
return $this->hasOne(Organization::className(), ['id' => 'organization_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getRelation()
{
return $this->hasOne(Relation::className(), ['id' => 'relation_id']);
}
}
You need to rename your getRelation() method as, you are overriding yii\db\ActiveRecordInterface::getRelation($name, $throwException = true). So this will cause an exception that getRelation method has an invalid declaration.

Categories