using Auth::id() Eloquent only when creating and updating - laravel-5

i need help in using Auth::id() Eloquent only when creating and updating.
what i am trying to achieve is, when i use Eloquent model save or update, the current logged in user id to be added to touched_by field.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
class Account extends Model
{
use SoftDeletes;
public function __construct(array $attributes = array())
{
$this->setRawAttributes(array_merge($this->attributes, array(
'touched_by' => Auth::id()
)), true);
parent::__construct($attributes);
}
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = ['deleted_at'];
}
But this will give me the current loggedin user when i do Model::all() ?

Related

Why I'm getting a null value when querying a model in eloquent?

I have a problem where I'm getting a null value when querying a model in eloquent, I have a two models User.php and Project.php, When I use tinker and use User.php to check if the data has a relation to Project.php model I got what I want, but when I use the Project.php to check if it has a relation to User.php I'm getting a null value.
This is my code for Project.php :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
public $table = "project";
protected $guarded = [];
public function owner(){
return $this->belongsTo(User::class);
}
}
And this is my code for User.php:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
public function projects(){
return $this->hasMany(Project::class);
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* 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',
];
}
This is my result in Tinker:
This is the result when I use tinker and query, as you can see my User.php has a relation to Project.php, But when I use Project.php I'm getting null value.
Have you tried with:
public function owner()
{
return $this->belongsTo(User::class, 'user_id');
}
Because (quote from the docs):
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _ followed by the name of the primary key column.
You should use eager loading to load parent relationship like this :
Project::with('owner')->first()->owner
And confirm that the foreign keys is correct

Laravel relationships not working as expected

So I have been building this simple Guest book where people leave comments. Ive linked the user model to the comment model and have tried returning the user that posted the comment however I always get an error. Ive made a Ticketing program before this using the same code and it worked and works fine still. See below
Comment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function user()
{
return $this->belongsTo('User::class');
}
}
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function comments()
{
return $this->hasMany(Comment::class);
}
}
And this is the controller where I am trying to return the results
<?php
namespace App\Http\Controllers;
use App\Comment;
use App\User;
use Auth;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
$comments = Comment::all();
$user = Auth::user();
$test = User::all();
$average = number_format((Comment::avg('rating')),2, '.', '');
dd($comments->user);
return view('welcome')->withComments($comments)->withUser($user)->withAverage($average);
}
}
Everytime I try and DD the result I get the error
Property [user] does not exist on this collection instance.
I am 100% stumped why this will work on one project and not another. I even rebuilt this little app to see if it was something I had done and I still get the same result.
You're trying to get property of a collection, not an object. So do this:
foreach ($comments as $comment) {
dump($comment->user); // $comment is an object
}

How to add a custom attribute to Auth::user() when one logs in

So, first I hope my title is not misleading. Please let me know if my title fits the question.
QUESTION.
I'm using Laravel 5.3 and I'm trying to find a way to add an attribute "role" to Auth::user() so that I can access it like
Auth::user()->role.
Role is not a field in the user table used for authentication but it's a value I calculate to get. The reason I ask is I don't want to calculate role every single time I need the value, instead I want to set it when authentication succeeds then reuse it.
Any idea how I can do this?
Or is there any way I can persist a value through out the time a user is logged in so that I can calculate it once and reuse it?
The best way you can achieve this is in your User.php model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token','is_admin',
];
protected function getRole(){
if(\Session::has("role")){
return Session::get("role");
}else{
//calculate and save role in session
}
}//end get Role
}//end class
so you will check it like this
Auth::user()->getRole();
Make sure you save the role in session after login , the getRole will get it and attach to the user() object , This doesnt need middleware too
Hope it helps
Just add the method of the keyword you want to use at the bottom of the model and use belongsTo() to link it up to a corresponding model. Then we just do Auth::user()->role() to use it. This is assuming you have a model called Role with a table and roles defined. (laravel 5.2+)
public function role() {
return $this->belongsTo( Role::class );
}
The entire model is here:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $guarded = ['id', 'remember_token'];
protected $hidden = [ 'password', 'remember_token' ];
public static $rules = array(
'email' => 'required|email|unique:users,email',
'first_name' => 'required|min:2',
'last_name' => 'required|min:2'
);
public static $rules_password = array(
'password' => 'required|min:6|confirmed'
);
public function role() {
return $this->belongsTo( Role::class );
}
}

Method roles not found in laravel Auth

I keep getting the method not found error when I'm trying to assign a role to the user in the user registration section.
The following is the code that I am using in the AuthController
namespace App\Http\Controllers\Auth;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
class AuthController extends Controller
{
protected function create(array $data)
{
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
])->get();
$user->roles()->sync([2]);
return $user;
}
}
following is my User model
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\HasRole;
use App\Role;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';
protected $fillable = [
'first_name','last_name', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
I'm not sure why this is happening. I think maybe it's not importing the User model properly, or I'm missing something. I'm new to laravel, so any help will be welcome.
To create a model simply use the following:
$user = User::create($attributes)
Notice that I did not call get() afterwords. get() will perform a query returning a Collection. I'm not sure what your Role model looks like, but it should work properly now.

How do I read database data from default User class in Laravel?

When I use the following code in my routes/web.php file, I keep getting the error of 'Trying to get property of non-object' each time I visit the /user/{id}/post url.
routes/web.php
use App\Post;
use App\User;
Route::get('/user/{id}/post', function($id) {
return User::find($id)->name;
});
App/User.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts() {
return $this->hasOne('Post');
}
}
App/Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
// protected $table = 'posts';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [''];
}
How do I view data stored in the table users? I put some dummy data in there to try and retrieve it.
If user hasOne relation with Post,it is better to make relation post() rather than posts() and post belongsTo user.
User Model:
public function post() {
return $this->hasOne('App\Post');
}
Post Model:
public function user()
{
return $this->belongsTo('App\User');
}
then, this gives all user's post along with user name.
$users=User::with('post')->get();
foreach($users as $user)
{
print_r($user->name);
print_r($user->post);
}

Resources