How to get a custom value using the method Auth in Laravel? - php

In my laravel project, when i want to get the current user ID, i use this logic bellow:
public function showuserid() {
$userid = Auth::id(); //this is the simplest way i found of how to get the current user's id
return view('perfil/mostrarid')->with('mostrarid', $userid);
}
My problem is, my table 'users' in my database, has an extra column called 'credencial'.
I tried to do $userid = Auth::credencial(); but it doesn't work and i get an error:
Method Illuminate\Auth\SessionGuard::credencial does not exist.
Can i get that value using Auth somehow? Is there any other way, as simple as Auth, to get the value?

My problem is, my table 'users' in my database, has an extra column called 'credencial'.
You need to access a logged-in user's property. To do so, try this:
$credential = Auth::user()->credential;
Now, in order to avoid to throw the error:
Trying to get property 'credencial' of non-object
Make sure that your user is logged-in. You could do this checking it first:
if (Auth::check())
{
$credential = Auth::user()->credential;
}

Related

Laravel 5.5 - Prevent additional attribute to be used during model update

The users table, besides others, have these fields: username, first_name, last_name. Each user can decide whether to show the username or the full name (first + last). This choice is stored inside a "settings" table.
To not perform repeated queries and calls to a function any time I need to show the name, I add the name to display to the user object as it is created, like $user->display_name = ... according to the user's choice.
The problem is that when the user updates the profile, Laravel tries to save this name inside a display_name field into the users' table, which doesn't exist and returns a 500 error. That also happens when the user tries to logout.
Is it possible to avoid that Laravel tries to store that value inside the database?
As suggested in other discussions I have already tried to give a default value to the attribute inside the User model, I've tried to set the attribute as protected, but nothing did work.
This is where the get{...}Attribute() function of a Model comes in handy. Say you want to access $user->full_name without actually saving full_name to the database. Since you have first_name and last_name, you can declare on your User model:
public function getFullNameAttribute(){
return $this->first_name." ".$this->last_name;
}
Laravel will parse what's between get and Attribute into a property available on the model, in this case either $user->full_name or $user->fullName.
To translate this to your use case, you can use something like:
In your User.php model:
public function getDisplayNameAttribute(){
if($this->settings == "use_full_name"){
return $this->first_name." ".$this->last_name;
} else if($this->settings == "use_username"){
return $this->username;
}
return "Not Configured...";
}
Note: You'll have to configure your if statements to determine what to return based on your settings.
Somewhere in a controller or view, you can call $user->display_name to have one of 3 things (determined by the logic/return statements above) displayed:
public function example(){
$user = User::first();
dd($user->display_name);
// $user->first_name." "$user->last_name, $user->username or "Not Configured..."
}
By doing this, when you access your $user, it will have a display_name property available that doesn't actually exist on the model, so you won't run into issues should you call $user->save();

Why can't I use Related Model created with same request in Laravel?

I have one table in which I store password reset tokens. There are 4 fields in that table. They are user_id , token , created_at and updated_at.
What I want to do is, Check if user already has password reset token or not. If a user already has password reset token, I want to send an email with the same token. If a user does not have a token, I want to create token and then send the email.
Problem is, I can send the email if token is already created. But, I am getting the error Trying to get property of non-object (View: /var/www/html/project_name/resources/views/emails/passwordResetLink.blade.php).
Why can't I access the password reset token with $user->passwordResetLink->token directly after creating the record in the database? Here is my code.
$user = User::findByUsername(request('username'));
if($user)
{
if(count($user->passwordResetLink))
{
$user->passwordResetLink->save();
}
else
{
$token = md5(str_random(16));
$record = new PasswordReset;
$record->user_id = $user->id;
$record->token = $token;
$record->save();
}
Mail::to($user)->send(New \App\Mail\PasswordResetLink($user));
return 1;
}
I am trying to access user's password reset token using $user->passwordResetLink->token. It's working fine if the record is already created but not working if the record does not exist.
PS: I am using save() because touch() isn't working because I don't have id field in my password_resets table in the database. let me know what's wrong with the code. I know save() won't work as I am not updating anything!
UPDATE: I solved my error by replacing the Mail line to Mail::to($user)->send(New \App\Mail\PasswordResetLink(User::find($user->id)));.
You change a related model after loading the primary model, this will cause the relation of the primary model to be outdated, one could solve this by reloading the relationship.
In your case you could use:
$user->load('passwordResetLink');
before
Mail::to($user)->send(New \App\Mail\PasswordResetLink($user));
This will reload only the PasswordResetLink and prevent having to reload the whole object.

Pass the data in the many to many relation ship in laravel

I have create a form that will show the user the event title, event description. And the code
public function show($id){
$showevents = Events::findOrFail($id);
return view('events.show',compact('showevents'));
}
This data i pass dont have the user data, but it will give me the specific event data. My question is how to pass the user data along with this?
Because my event table dont have the user information, it all in the user table.
I try {{$showevents->user->name}} in the view form, but it doesnt give me the information of the user.
You will be needing the user-id too if you want to retrieve infomation about the user and send it to the view file..
One thing you can do for getting the user-id anywhere is setting the user-id in Session variable when the user logs-in as:
\Session::set('user_id',$userID);
Then you can get the user-id anywhere in any controller using
$id = \Session::get('user_id');
For example in your case
public function show($id){
$user_id = \Session::get('user_id');
$user = User::findOrFail($user_id);
$showevents = Events::findOrFail($id);
return view('events.show',compact('showevents','user));
}
Now where you will set the Session variable depends entirely upon your code..I used to set after a user has logged in successfully and also rembember to remove session data when logging out as..
\Session::flush();
First of all {{$showevents->user->name}} of course will fail because you don't have any connection between events and user.
If you want to make connection between it you going to need user_id inside event table.
If you want to get user data but don't have any connection, you need to do in seperate query.
$user = User::findOrFail($user_id);
return view('events.show',compact('showevents', 'user'));
You should use Eloquent's relationship functions or wrap them inside you Models relationship functions and use them.
check the Laravel documentation

model with user id laravel

I am developing an application where I want to get all of a user's open tasks and display them. I have created a new view, route, controller and model, but I can't get the model to work right, especially as it pertains to getting the current user's ID for the SQL query.
app/models/Task.php
class Task extends Eloquent
{
public static function open()
{
$id = Auth::user()->id;
$tasks = DB::table('tasks')->where('c', 0)->where('user_id', $id)->get();
return $tasks;
}
}
Also
app/controllers/TaskController.php
public function open()
{
$tasks = Task::open();
return View::make('tasks.open')->with('tasks', $tasks);
}
Error: Trying to get property of non-object - looks like on the $id = Auth::user()->id;
What's the correct model?
Looks like not being logged in was the problem - this model works.
Because this will probably help someone else in the future: when you create a user's account, use Hash::make when you add the password to the database, because when you use Auth::attempt in your log in method, Laravel hashes password the user typed and compares the two, and if they're both not hashed, it won't log the user in.

Update Specific Attributes or Fields

PROBLEM 1:
When I try to save() any Yii Model, it updates all fields in the row.
The problem is: When I try to save model users, even if has no PASSWORD to update, it get the database value(already hashed) and hash again.
How can I do to YII only update fields that I want?
Code:
$user = Users::model()->findByAttributes(array('username'=>$this->username));
$user->ip = $_SERVER['REMOTE_ADDR'];
$user->save();
Users.php (Model):
public function beforeSave() {
if (!empty($this->password))
$this->password=$this->hashPassword($this->password);
return true;
}
PROBLEM 2:
I have an API that can create USERS.
API Tutorial: http://www.yiiframework.com/wiki/175/how-to-create-a-rest-api/
When I have crypter_password in the database, instead password, I got the error: Parameter password is not allowed for model Users, because the API validate parameters using $model->hasAttribute().
How can I fix the API actionCreate to allow custom parameters?
According to Yii's doc: http://www.yiiframework.com/doc/api/1.1/CActiveRecord#save-detail
public boolean save(boolean $runValidation=true, array $attributes=NULL)
$attributes - array - list of attributes that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved.
You can pass in an array of fields that you want to save.
Eventhough the other answers listed here are not wrong, they are definitely not really developer friendly and it's extremely easy to forget to add the attributes to the save line.
Here is a developer friendly way of working.
In your model, add the following attribute:
private $_aAttributesBackup;
In this variable, we will store an exact copy of the current model. To do this, the following afterFind method needs to be added:
public function afterFind()
{
$this->_aAttributesBackup = $this->attributes;
}
Almost there. At this point, the model will store all of his attributes in the attributesBackup field which makes it easier to compare. To make it easier, we also need a method that will check if the specified attribute has a backup value. We do this by adding the following code into our model:
public function getOriginalAttribute($sAttribute)
{
if ($this->_aAttributesBackup)
{
return $this->_aAttributesBackup[$sAttribute];
}
return NULL;
}
Now, how about checking if the password has been changed? Simple, by adding the following beforeSave code:
public function beforeSave()
{
if ($this->getOriginalAttribute('password') != $this->password)
{
$this->password = sha1($this->password);
}
return parent::beforeSave();
}
Et voila. Now everytime you execute the code $Model->save(); the system will check if the password has been changed, If the password is changed, it will hash it again, if it is not changed, it won't be hashed again.
Save () inserts a row into the database table if its isNewRecord property is true. Otherwise, it will update the corresponding row in the table (usually the case if the record is obtained using one of those 'find' methods.)
What you have to do is update specific field so you can use SaveAttributes and it accepts the array of string values that have been updated for example demo code is as follow
$user = Users::model()->findByAttributes(array('username'=>$this->username));
$user->ip = $_SERVER['REMOTE_ADDR'];
$user->SaveAttributes(array('ip'));

Categories