User Permission After Registration in Laravel - php

In my database i have this
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('admin')->nullable();
$table->string('usertype')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Which means in my form i have this
<select name="usertype">
<option>Select Usertype</option>
<option value="1">Landlord</option>
<option value="2">Agent</option>
<option value="3">Tenant</option>
</select>
Users can select the type of user they are.
I have this in my RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'usertype' => $data['usertype'],
'password' => Hash::make($data['password']),
]);
}
When a user which is landlord registers it takes them to http://127.0.0.1:8000/dashboard
How can i make the content different for each users i.e
1. I want landlord to be able to just add property
2. I want tenant to be able to edit profile, see properties they have bought.
3. I want agent to able to add property like landlord.
How can i achieve this ?

You can make use of Laravel Policies. Example if you have a PropertyController, you can have a PropertyPolicy with the method:
/**
* Determine whether the user can create models.
*
* #param \App\User $user
* #return mixed
*/
public function create(User $user)
{
return $user->usertype == 'Landlord';
}
And in the view, you can do something like:
#can('create', $property)
// link to create property
#endcan
learn more about Laravel Policies at https://laravel.com/docs/7.x/authorization#creating-policies

Related

Laravel SQL sign in issue

I've set up an admin log in but upon submitting the form i'm thrown an error. I've tried globally searching restaurant_users but i'm unable to find anything.
login controller:
public function login(Request $request) {
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('restaurantuser')->attempt(['email' => $request->email, 'password' => $request->password])) {
return redirect()->intended(route('dish.create'));
}
return redirect()->back()->withInput($request->only('email'));
}
schema:
Schema::create('restaurantuser', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
error:
SQLSTATE[HY000]: General error: 1 no such table: restaurant_users (SQL: select * from "restaurant_users" where "email" = admin#test.com limit 1)
If any other code is needed let me know and ill provide it.
In your User model add this:
protected $table = 'restaurantuser':
The restaurant_users comes from Laravel as it assumes that if your model is called RestaurantUser that that's the table name.
Hello fellow webApp student.
Would you be kind enough to share how you implemented the administrator role, and the corresponding account approval if you did end up completing it.
Much appreciated,
someone close by...

User fields seem empty when the user is has been registered

I added couple new columns to users table like role, suspended_at and banned_at. And then added them as fillable.
But when a new user is registered, the fields seems empty (except id,created_at and updated_at).
Here is the migration file
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string("username", 20)->unique()->index();
$table->string('email')->unique();
$table->string('password');
$table->string("role",15)->default("newbie");
$table->rememberToken();
$table->timestamps();
$table->dateTime("suspended_at")->nullable();
$table->dateTime("banned_at")->nullable();
});
User model
protected $fillable = [
'name', 'email', 'password', "username", "role", "suspended_at", "banned_at"
];
a small demo from users table.
+----+------+----------+-------+----------+------+
| id | name | username | email | password | role |
+----+------+----------+-------+----------+------+
| 4 | | | | | |
+----+------+----------+-------+----------+------+
RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
"username" => $data["username"],
'password' => Hash::make($data['password'])
]);
}
Shouldn't you add role, suspended_at, banned_at inside User::create to register. And also in your table you don't have suspended_at, banned_at column, please check once.
Instead of using default registration I am suggesting you to create your own controller php artisan make:controller UserController then add a post-url to indicate/trigger the function like Route::post('/register', UserController#add_new_user) and then inside the controller you have to call the model by adding use App\User before class UserController extends Controller and inside the class create your own function like below:
public function add_new_user(Request $request) {
$user = new User; //modal
$user->name = $request->name;
$user->username = $request->username;
$user->email = $request->email;
.
.
.
$user->save();
}

How to pass to the variable the Auth::user() method and sync into pivot table?

I can get the current user that logged in. But I don't know how can I passed this into variable. I can the user id by this.
public function getDocuments()
{
//GETTING ALL THE ID OF THE USERS IN THE DATABASE EXCEPT THE ID OF CURRENT USER.
$resultRecipient = DB::table('users')->where('id', '!=', Auth::id())->get();
//GETTING ALL THE CATEGORIES.
$resultCategory = DB::table('categories')->get();
//VIEW
return view ('document.create')->with('resultRecipient', $resultRecipient)->with('resultCategory', $resultCategory);
if(\Auth::user()->id)
{
echo "You get the id";
}
else
{
echo "Failed";
}
}
Can anyone tell me how can I sync the current user id when the submit button is submitted. Is there a way how can I attach the id of the user in the sync method?
public function postDocuments(Request $request)
{
$this->validate($request,
[
'title' => 'required|alpha_dash|max:255',
'content' => 'required',
'category_id' => 'required',
'recipient_id' => 'required',
]);
$document = new Document();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category_id;
$document->save();
$document->recipients()->sync($request->recipient_id, false);
return redirect()->back();
}
UPDATE!
According to #Ariful. I can add the instance of Auth::user(); to get the id. But it doesn't return me the id to my pivot table and gives me a error.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (webdev.document_user, CONSTRAINT document_user_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE) (SQL: insert into document_user (document_id, user_id) values (59, 0))
public function postDocuments(Request $request)
{
$this->validate($request,
[
'title' => 'required|alpha_dash|max:255',
'content' => 'required',
'category_id' => 'required',
'recipient_id' => 'required',
]);
$user = Auth::user();
$document = new Document();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category_id;
$document->save();
$document->recipients()->sync([$request->recipient_id, $user->id, false]);
return redirect()->back();
}
Models:
User Model
class User extends Model implements AuthenticatableContract
{
public function documents()
{
return $this->belongsToMany('App\Models\Document', 'document_user', 'user_id', 'document_id');
}
}
Document Model:
class Document extends Model
{
public function recipients()
{
return $this->belongsToMany('App\Models\User', 'document_user', 'document_id', 'user_id');
}
}
Migration:
User migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('middle_name');
$table->string('email');
$table->string('username');
$table->string('address');
$table->string('password');
});
}
Documents migration:
public function up()
{
Schema::create('documents', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
}
documents_user migration:
public function up()
{
Schema::create('document_user',function (Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('document_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('document_id')->references('id')->on('documents')->onDelete('cascade');
$table->unsignedInteger('sender_id')->nullable();
$table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade');
$table->dateTime('dateReceived')->default(DB::raw('CURRENT_TIMESTAMP'));
});
}
Screenshot Database:
UPDATE 2:
I can insert a values on my user_id based on the user's choice in the select list.
This is where the values of the form inserted in the user_id column. I just need to insert the current user in my sender_id so I can determined who send the data.
<div class = "form-group">
<label for = "recipient_id" class = "control-label">To:</label>
<select name = "recipient_id[]" multiple class = "form-control" id = "myUserList">
#foreach ($resultRecipient as $list)
<option value = "{{ $list->id }}">{{ $list->username }}</option>
#endforeach
</select>
</div>
As you can see here I just insert this manually based on the users table data. Still don't have idea how can I insert the current user into sender_id column.
I believe this should work
$user = Auth::user(); //get current user
$document->recipients()->sync([$user->id]);
UPDATED Source Link
$document->recipients()->sync( [ $request->recipient_id, $user->id ], false );
As per documentation,
The sync method accepts an array of IDs to place on the intermediate table.
UPDATE 2
$document->recipients()->sync( [ $request->recipient_id =>
['sender_id' => $user->id] ],
false );
Your sender_id is not part of your relationship. So you need to add it as extra info.
UPDATE 3
After discussion, this should be your main code
foreach($request->recipient_id as $receipentId){
$document->recipients()->sync( [ $receipentId =>
['sender_id' => $user->id] ],
false );
}
This will loop through your receipent_id array and take each id for sync with the current logged in user as $user->id;

Laravel 5.1 AuthController Validate and Create

I am having trouble in laravel 5.1 registration in the AuthController the validate and create method. I make may login and register forms in one page so I added register- on the inputs of the registration form (ex. register-email for the email address in the registration form). So my validate method in the AuthController is this:
App\Auth\Http\Controllers\Auth
/**
* 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, [
'last-name' => 'required|between:2,35',
'first-name' => 'required|between:2,35',
'register-email' => 'required|email|max:255|unique:users',
'register-password' => 'required|confirmed|min:8',
'register-confirm-password' => 'same:register-password'
]);
}
The last-name, first-name, register-email, etc is a html inputs right? So I think this is right?
and then this is the create method:
protected function create(array $data)
{
return User::create([
'last-name' => $data['last-name'],
'first-name' => $data['first-name'],
'email' => $data['register-email'],
'password' => bcrypt($data['register-password'])
]);
}
The keys in the create method is the database table right? and the value is the html input name/id? I am getting Unknown column error of register-email why is that? I know I don't have register-email column in the database but, in the create method I specify the email column in the database and not register-column which is the html input name of my registration form. Please help.
BTW this is my database migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('last-name');
$table->string('first-name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}

Laravel 5 not storing checkbox value

We are having a strange issue with Laravel 5 in that it is refusing to store the checkbox value.
We are adapting the existing registration form that comes bundled with Laravel 5 and we are adding an optin checkbox but it seems the model does not recognise this as a field even though we are adding it as a field in the migration file.
Any help on this would be appreciated.
Mirgration File:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('password', 60);
$table->date('dob');
$table->boolean('optin')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
Then we add it to the register.blade.php file:
<div class="form-group">
<label class="col-md-4 control-label">Optin</label>
<div class="col-md-6">
<input type="checkbox" class="form-control" name="optin">
</div>
</div>
At the point of creating the User model, we check the value of the checkbox and assign it.
protected function create(array $data)
{
//this does return 1 or 0 as expected
$optin = ($data["optin"] == "on") ? 1 : 0;
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'dob' => $data['dob'],
'optin' => $optin
]);
}
But at this point the field is null. No value is entered into the database...
Have you put the field 'optin' in the $fillable array within the model? Otherwise you cant create a User with 'optin' using the static create method.
//File: User.php
protected $fillable = ['optin'];
The model already has a static create() function. Therefore, when you make a call like User::create($data) from your controller, your function is not called.
My approach is to change the name of your function and make it static.
Update
Also you can override the create function:
public static function create(array $attributes)
{
$attributes["optin"] = ($attributes["optin"] == "on") ? 1 : 0;
return parent::create($attributes);
}

Categories