How to create a row for user in another related table when the user is created in laravel? - sql

I need to create a row in a related table. This is a hasOne and belongsTo relationships.
A user hasOne profile
A profile belongsTo user
I want to create a profile row once the user has been created.
public function store(UserRequest $request)
{
$user= new User();
User::create($request->all());
Profile::create([
'user_id' => $user->user_id,
]);
return redirect()->route('users.index')
}

you can use events(observer) in laravel for doing your work when User created in any where of your project.
https://laravel.com/docs/5.3/eloquent#observers

Use Model Observers.
You can declare an observer to created event, and create the profile there.
public function creating($model)
{
// Create your related profile.
// Note that profile relationship must be defined at your model class
$model->profile()->create();
return true;
}
This observer may be created either on a Model Observer Class, or declared on model boot.

Try like this:
public function store(UserRequest $request)
{
$user = User::create($request->all());
$user->profile()->create([]);
return redirect()->route('users.index')
}
You have to have hasOne relation method in user's class:
public function profile()
{
return $this->hasOne(Profile::class);
}
This for update is not working; Is there a solution
public function update(Request $request, $id)
{
$input = $request->all();
$employee = Employee::findorfail($id);
$update = $employee->update($input);
$employee->personaldetail()->update(['employee_id' => $employee->employees_id,]);
return redirect()->route('employees.index')->with('message','Employee has been updated');
}

Related

How to get the default $id from another table using laravel model relationship?

I am facing the problem whereby I don't know the syntax of letting the id of my property model equals to property_id value in property_doc table.
In PropertyDoc model
public function property()
{
return $this->belongsTo(Properties::class, 'property_id');
}
In Properties model
public function property_id()
{
return $this->hasMany(PropertyDoc::class, 'property_id');
}
In PropertyController
public function StoreInfoProperty(Request $request)
{
$propertyInfo = new PropertyDoc;
$propertyInfo->property_id = $property_id;
}
I am stuck at retrieving the default id value in properties database to be equal to the property_id in property_docs database. Thank you.
You should change the naming of the relationship, see my example below:
In Properties model
public function propertyDocs()
{
return $this->hasMany(PropertyDoc::class, 'property_id', 'id');
}
In PropertyDoc model
public function property()
{
return $this->belongsTo(Properties::class, 'property_id', 'id');
}
In controller
public function StoreInfoProperty(Request $request)
{
$propertyDoc = PropertyDoc::with(['property'])->where('...logic here');
$property_id = $propertyDoc->property->id;
}
hope can help you and happy coding !

Return result from pivot table

I have multiple campaigns, that can be assigned to multiple users. Basically, they have belongsToMany relation both ways.
I would like to print out the results on the page, that only belongs to that specific user, based on the pivot table.
Models:
User model:
public function campaign()
{
return $this->belongsToMany(Campaign::class, 'campaign_user');
}
Campaign model:
public function users()
{
return $this->belongsToMany(Gift::class, 'campaign_user');
}
Migration of pivot table:
public function up()
{
Schema::create('campaign_user', function (Blueprint $table) {
$table->foreignId('user_id')->constrained()->onDelete('cascade');;
$table->foreignId('campaign_id')->constrained()->onDelete('cascade');
});
}
Incorrect Controller:
public function index(Request $request)
{
$data = Campaign::withCount('gifts');
$data->where('user_id', $request->user()->id)->get();
return view('subscribes.index', ['data' => $data]);
}
Basically, all I need, is to return specific campaigns, that the client has subscribed only, based on the pivot table/user id. Thus, editing this Controller.
I still face lots of issues with Eloquent models and pivot tables, and I would be very thankful, for any assistance in regards to it.
This will make more sense if you rename the relationship campaign() to it's plural campaigns() on your User model.
Once you have the relationships set up, you can access campaigns for the user straight from the user object.
$user = $request->user();
$data = $user->campaigns;
Note also, if your user is authenticated, you can access them easily like:
$user = auth()->user();
So your index method in your controller would be
public function index(Request $request)
{
$user = $request->user();
$data = $user->campaigns;
return view('subscribes.index', ['data' => $data]);
}

How to attach more the role to same user?

I can add only one role using :
$user->attachRole($request->role_id);
But I need to make role accept being admin and up-loader in the same time for example.
This is User controller
public function store(UserRequest $request)
{
$request->merge(['password'=>bcrypt($request->password)]);
$user = User::create($request->all());
$role_id=$request->input('role_id'); //added by me
$user->attachRoles(['admin', $request->role_id]);
// $user->attachPermissions($request->permissions);
session()->flash('success','Data added successfully');
return redirect()->route('dashboard.users.index');
} //end of store
result is ONLY ONE ROLE APPERARS

CakePHP - Best way to Call API in controller?

In Message Model, I have
id/Subject/Comment/SenderID/RecipientID
So in Message Controller
public function index(){
$msgs = $this->Message->find();
$this->set('msgs', $msgs);
}
In Message view
foreach ($msgs as $msg)
echo ...
endforeach
BUT instead of outputting sender ID and recipient ID, I want to be able to get the username via an API which has already been set up, http://domain.com/userid/1, it will return the username in a json.
I know it's a bad practice to do this in view, but can you suggest how should I do this in controller?
Create a model for your API calls, tell cake not to look for a db table for it and have the function with the logic to pull the username there.
App::uses('AppModel', 'Model');
class MyAPI extends AppModel {
public $useTable = false;
public function getUserNameForID(Int $id = null) {
//Your logic here
return $userName;
}
}
Then in your controller you need to load the MyAPI model and pass it your data recursivly
$this->loadModel('MyAPI');
foreach (...) {
...
$userName = $this->MyAPI->getUserNameForID($userID);
...
}

how to get or create role in yii

I am a newbie to yii. I have stuck my mind with yii-tutorials for creating roles in yii. but I am not getting how can I create role in yii. means I want to create two roles admin & staff and I want to give different priviliage to them.
I have created a role in user table, but I am not getting that how can I create a role and can assign priviliages to them, please help me guys
Thanks in advance
In your copenents/UserIdentity.php
class UserIdentity extends CUserIdentity{
private $_id;
public function authenticate()
{
$record=Members::model()->findByAttributes(array('username'=>trim($this->username)));
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($record->password!==md5(trim($this->password)))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$record->id;
$this->setState('username', $record->username);
$this->setState('name', $record->name);
$this->setState('type', $record->role);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
public function setId($id)
{
$this->_id = $id;
}
}
You can create a new column name as "role". set the members type "admin" or "staff" to role column.
Be careful to that line.
$this->setState('type', $record->role);
Create a new helper file. /protected/helpers/RoleHelper.php
class RoleHelper {
public static function GetRole(){
if (Yii::app()->user->type == "admin"){
//set the actions which admin can access
$actionlist = "'index','view','create','update','admin','delete'";
}
elseif (Yii::app()->user->type = "staff"){
//set the actions which staff can access
$actionlist = "'index','view','create','update'";
}
else {
$actionlist = "'index','view'";
}
return $actionlist;
}
}
and in your controllers -> accessRules function
public function accessRules()
{
return array(
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array(RoleHelper::GetRole()),
'users'=>array('#'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
and dont forget to add 'application.helpers.*' to /config/main.php
'import'=>array(
'application.models.*',
'application.components.*',
'application.helpers.*',
),
This source is pretty good specially for beginners..I am using this method till now:
Simple RBAC in YII
Just follow the instructions given while having your desired modifications.
Concrete Example:
WebUser.php (/components/WebUser.php)
<?php
class WebUser extends CWebUser
{
/**
* Overrides a Yii method that is used for roles in controllers (accessRules).
*
* #param string $operation Name of the operation required (here, a role).
* #param mixed $params (opt) Parameters for this operation, usually the object to access.
* #return bool Permission granted?
*/
public function checkAccess($operation, $params=array())
{
if (empty($this->id)) {
// Not identified => no rights
return false;
}
$role = $this->getState("evalRoles");
if ($role === 'SuperAdmin') {
return 'SuperAdmin'; // admin role has access to everything
}
if ($role === 'Administrator') {
return 'Administrator'; // admin role has access to everything
}
if ($role === 'Professor') {
return 'Professor'; //Regular Teaching Professor, has limited access
}
// allow access if the operation request is the current user's role
return ($operation === $role);
}
}
Just connect it with your components/UserIdentity.php and config/main.php:
'components' => array(
// ...
'user' => array(
'class' => 'WebUser',
),
and thats it..
to check the role of the logged in:
Yii::app->checkAccess("roles");
where checkAccess is the name of your function in WebUser...
Please note that evalRoles is a column in your table that will supply the role of an account (on my link provided, that would be the word roles used in the major part snippet)