Laravel: How to insert data on click on href link using route and controller - html

After Click On "Yes I am Sure" button data not inserting into database
Here Is my code Auth user block another user from viewing their profile.
so, i am inserting data auth username and block user username into data after click on "Yes I am Sure" but data is not inserted.
my .blade file profile/index.blade.php
here "Yes I am Sure" href link to go on route
<div class="cd-popup" role="alert">
<div class="cd-popup-container"><br>
<div class="content_block">Are you sure you want to block this person?</div><br>
<div class="content_block_instruct">Hide content and notifications from this user.</div><br>
<ul class="cd-buttons">
<li> Yes I am Sure!</li>
<li>Cancled</li>
</ul>
Close
</div> <!-- cd-popup-container -->
</div>
Route File
Route::post('/{username}', [
'uses' => 'Profile\UserProfileController#blockUser',
'as' => 'profile.index',
]);
Controller file
Whose username show on URL, with their username check BlockUser model if block_username and URL username same data not inserted else data not same their data inserted into database
public function blockUser(Request $request, $username)
{
$blocked = User::where('id', Auth::user()->id)->first();
if (blockuser::where('block_username', $username)->first()){
}else{
$blocked = new blockuser;
$blocked->user_username = Auth::user()->username;
$blocked->block_username = $username;
$blocked->save();
}
$user = Auth::user();
$userprofile = userprofile::where('user_id', Auth::user()->id)->first();
return view('profile.index',compact('user', 'userprofile'));
}
Here is my User Model
public function blockuser(){
return $this->hasOne( BlockUser::class);
}
BlockUser Model
use App\User;
class BlockUser extends Authenticatable
{
public $timestamps = false;
protected $fillable = [
'user_username', 'block_username',
];
public function user()
{
return $this->belongsTo( User::class, 'username' );
}
}
Database table block_users
id user_username block_username
1
2

Clicking simply on link actually makes GET HTTP Request. You need to change fromRoute::post(...) to Route::get(...). If you still want to have post method, then make simple ajax call with post method on onclick event of the anchor tag.

Related

Laravel 5.2 how to update my User table

I am trying to update my rows. The figure provided is the Users table structure. When I register using Laravel Authentication. Only the yellow marked rows are used and others remain empty. I have a created another page called profile and want to add data to the remaining empty rows using a profile page. But I am stuck and can't figure out how to do it. Any suggestions?
You can create Profile controller for interaction with User table from profile page, like this:
use App\User;
class ProfileController extends Controller {
public function function_name(Request $request)
{
...
$user = Auth::User(); //get authorized user, or you can get user by ID
$user->city = 'City';
$user->country = 'Country ';
$user->save();
...
}
In your user model, dont forget to add thoes fields to fillable variable;
for exemple
protected $fillable = [
'name', 'email', 'password', 'company_name','street_name','whatever'
];
this way the ->create($data); method will work just fine
or you can just add those fields to registration form and update your registration method

Action after loginByCookie()

In my app, I'm using session to store some user's data (e.g. name, role). I'm using default User class on common/models from yii2 and I'm getting the data I need by user id.The problem is that the data I stored in session are lost if user resume their previous session without entering password (using remember me option). To solve this, I tried to modify and put the codes for saving user's data inside validateAuthKey() method in User since it's called when yii2 checking for authkey to resume session. As in:
public function validateAuthKey($authKey)
{
$user = Member::findOne(['account_id' => Yii::$app->user->id]);
// Save on session
Yii::$app->session->set('name', $user->first_name . ' ' . $user->last_name);
Yii::$app->session->set('position', $user->position);
// .. other data
return true;
}
As you can see, I use the id of logged user to find Member. But by doing this, I got "Trying to get property of non-object" exception from Yii::$app->user->id. I can only get the id after the login process is completed. After prying around, I found that loginByCookie() from User in vendor\yiisoft\yii2\Web is used to log in. Is there any way to save user's data without tampering codes on vendor? Maybe some kind of event after loginByCookie() is executed.
Create your own User model extends \yii\web\User
namespace frontend\components;
class User extends \yii\web\User
{
protected function afterLogin($identity, $cookieBased, $duration)
{
...Do something here...
parent::afterLogin($identity, $cookieBased, $duration);
}
}
Modify the config (main.php).
'components' => [
'user' => [
'class' => 'frontend\components\User',
'identityClass' => 'common\models\User',
...
]
]
Put the below code in common/config/bootstrap.php
The EVENT_AFTER_LOGIN will be called even if the user is logged in by cookie.
use yii\web\User;
use yii\base\Event;
Event::on(User::className(), User::EVENT_AFTER_LOGIN, function() {
$user = Member::findOne(['account_id' => Yii::$app->user->id]);
// Save on session
Yii::$app->session->set('name', $user->first_name . ' ' . $user->last_name);
Yii::$app->session->set('position', $user->position);
});

yii2 advanced login function always returns invalid username and password

I made no changes in yii login function but it returns error while giving correct username and password
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->render('index');
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
Try to use:
return $this->redirect(['site/index']);
instead return $this->render('index');
I've faced the same problem. For advanced template default signup scenario you need to activate your account by email confirmation (the email you provided at the time of signup). Until that moment your status is inactive. This status is used for login - only active users can log in.
If you're using this project for local purposes, you may change the status of your record in db table 'user' from 9(inactive) to 10(active). Then you will be able to login.
may me problem inside your user model, check validatePassword Or findByUser functions

How to update the changed username in session variable without logout or session destroy

Question:
How to update the changed username in session variable without logout or session destroy ?
For Example:
I am login with username "Ram" and this username storing in session variable User_Name,after logged in i am changing my username "Ram" into "Kumar". So this newly changed username should get updated in session variable User_Name automatically without logout from my account.
Sample Controller Code for Login:
function check_database($password)
{
// Field validation succeeded. Validate against database
$username = $this->input->post('username');
// query the database
$result = $this->civic_soft_model->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'UID' => $row->UID,
'User_Name' => $row->User_Name,
'User_Type' => $row->User_Type,
'User_OTP' => $row->User_OTP
// 'Login_Status' => $row->Login_Status
// 'Node_Id' => $row->Node_Id
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
NOTE:
I am using PHP,MySQL and CodeIgniter MVC Framework.
Please Help Me Friends...
I actually see what the problem is now. You are setting 'logged_in' to be an array. Not sure if that's common, but what I usually do is set 'logged_in' as a boolean and I set userdata the data that I need in another array.
However, for you case you can try this:
$newUserData = $this->session->userdata('logged_in');
if (is_array($newUserData)) {
$newUserData['User_Name'] = $new_username;
$this->session->set_userdata('logged_in', $newUserData);
}
For better usability, I would addd a function to $this->civic_soft_model called "updateUser" or something of that nature. And when that function is called, you can update all of the session data that you need to.
Insert this function to your controller and call it whenever there is an update made on the users information.
//$new_username : the username inputted by user when he is trying to update his account
function update_session($new_username){
$this->session->set_userdata('User_Name', $new_username);
}

Get only personal record of the DB and not all of the records

When you log in on my site, you'll directly be directed to your profiles page. So that you can see your name, phone, email, etc. But at the moment when I log in on my site, I get directed to my profile page but I get all data for every user in my DB. So I'm getting the name of every user, the phone of every user, etc. I only want to get the data of the person who logged in. How can I achieve this?
I did some thinking about it, and came up with doing a where userID = ID of the user HERE
But I don't know where I'll be able to get the ID of this user. When logging in I'm starting a session, so would I need to store the logged in users ID in the session? Or isn't that secure?
I'm learning and working with CodeIgniter, so I'm doing it in a MVC pattern.
Controller where I login and set my session
if($query){
$data = array(
'username' => $this->input->post('loginEmail'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
Controller
if($logged_in){
//if the user is logged in
$this->load->model('profile_model');
if($query = $this->profile_model->userInfo()){
$data['records'] = $query;
$data['content'] = 'profile_view';
$this->load->view('templates/template', $data);
}
}
Model
class Profile_model extends CI_Model{
function userInfo(){
$query = $this->db->get('tbl_users');
return $query->result();
}
}
View where my I want to show my data
if(isset($records)){
foreach($records as $row){
echo $row->username;
echo $row->cellphone;
}
}
All you are missing is a WHERE statement in your model. As an argument for the WHERE statement you can use your session variable containing your email address(assuming your database table stores emails in a field called 'username':
class Profile_model extends CI_Model{
function userInfo(){
$this->db->where('username', $this->session->userdata('username'));
$query = $this->db->get('tbl_users');
return $query->result();
}
}
Or you can pass the email/username to the model from the controller:
if($logged_in){
//if the user is logged in
$this->load->model('profile_model');
$username = $this->session->userdata('username');
if($query = $this->profile_model->userInfo($username)){
$data['records'] = $query;
$data['content'] = 'profile_view';
$this->load->view('templates/template', $data);
}
}
and then in your model:
class Profile_model extends CI_Model{
function userInfo($username){
$this->db->where('username', $username);
$query = $this->db->get('tbl_users');
return $query->result();
}
}
I don't know what your columns are named in your database, or I could be more precise.
If usernames in the database are different from email addresses, change the line in the model to:
$this->db->where('email', $username);
Hope this helps!