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.
Related
I'm trying to learn Spatie Laravel Permission Package. When trying to insert data to models has permissions table it gives the below error in postman. I don't know clearly how to insert data. I used the guide of spatie documentation.
error,
Call to a member function givePermissionTo() on null
here is my controller function
public function models()
{
Role::create(['name'=>'writer']);
Permission::create(['name'=>'edit post']);
Auth::id()->givePermissionTo('edit articles');
return 'hello';
}
I don't know if the question is clear enough. Please tell me if it's not clear.
Auth::id() return the id of the authenticated user, but you need to call givePermissionTo on a user object, not a user id.
try
Auth::user()->givePermissionTo('edit articles');
#brombeer was right. the issue was in the Auth::id() It says the authenticated user is not accessed in.
I changed my function line Auth::id()->givePermissionTo('edit articles'); to auth()->user()->givePermissionTo('edit articles');. Also the called __construct() function like this,
public function __construct()
{
$this->middleware('auth');
}
Then I accessed as an authorized user and inserted log in the token as a bearer token in postman. Then the issue was fixed.
Auth::id returns the id of the user. The method givePermissionTo should be called on an object of the user and not the id.
Here are two ways you can do it:
Method 1
Auth::user()->givePermissionTo('edit articles');
Method 2
$user = Auth::user();
$user->givePermissionTo('edit articles);
I am new to Laravel so please be patient with me.
i have to implement search functionality in Laravel. i am able to send form data to the search controller and receiving it as well
public function search_results(Request $request){
if ($request->has('gender')) {
echo $request->gender;
}
.....
}
Now when i am following tutorials on the web i am getting such examples :
public function filter(Request $request, User $user)
{
// Search for a user based on their name.
if ($request->has('name')) {
$user->where('name', $request->input('name'))->get();
}
}
or
public function index()
{
$users = User::where('status', 1)
->where('is_banned', 0)
->get(['name']);
dd($users);
}
now i am not sure from where this User:: or User $user is being added, and what should i do in my scenario.
Your suggestions would be helpful ..
Thanks
The $user represents an object belonging to the model(User::) associated with a table(users) in the mvc structure. If you want to "Search for a user based on their name." That means you already have a users table in database , and a User model .
You can use eloquent queries to retrieve data from database.
A User.php file should be generated when you create a new laravel project with composer. You can check for that.
So when you declare a variable like this :
$user = User::first();
You are actually getting the first element in 'users' table by using your User model.
If you can configure your User model and users table correctly , you should be able to get all records from your users table like this :
$users = User::all();
Then you can filter it like :
$users = $users->where('gender','male') // where('gender',$request->gender) in your situation
If you dont have a users table or a model , you can look to the document about how to create models using artisan commands Laravel API Doc. Generating Model Classes
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;
}
I want to create a relationship that checks if a user has liked a post. In order to do this, the relationship needs to check if the user is logged in, and then use their user_id to get the like record. Something like:
public function userLike() {
if (Auth::check()) return $this->hasOne('App\Like')->where('user_id', Auth::user()->id);
}
However, this doesn't work. Additionally, if the user is not logged in and this relationship is called (which it is by default), it will return an error.
What is the proper way of doing this?
If you want to conditionally load a relation then you can do so by lazy eager loading. In your example you could define the relation as
public function userLike() {
return $this->hasOne('App\Like', 'user_id');
}
Then in your controller (or wherever else) you can do the check for if the user is question is currently logged in user or not
$loggedInUser = auth()->user();
if($loggedInUser){
$loggedInUser->load('userLike');
}
Then you can continue with whatever you want to do with the loggedInUser and the userLike.
Say you have multiple users at a point (in your code) and you want to load the likes for only the currently logged in user then you can
//$users is a collection of multiple users - assumed
foreach($users as $user){
if($user->email === auth()->user()->email){
$user->load('userLike');
}
}
Hope this helps
This is how I would do that:
1) “likes” table
I would first create a table to store all the “likes” with columns for a “post_id” and a “user_id”
2) create the relationships
User Model
public function likes()
{
return $this->belongsToMany('App\Post', 'likes', 'user_id', 'post_id');
}
Post Model
public function likes()
{
return $this->belongsToMany('App\User', 'likes');
}
3) Post Controller - the method
I would do the followings:
check if user is logged in, otherwise throw an error
make sure post exists, otherwise throw an error
create a new entry in like table with user_id and post_id
(you can also check if the user is logged in directly on your route using a middleware)
4) In the view
I would call the controller method using an ajax call.
Not sure if I forgot something, but hopefully that can help you a little bit.
If you need to “like” more things than only post, check the polymorphic relationships.
I've used Eloquent hasOne to create a relationship between the user and the users_permissions table when the user register's to the website and group the user according to the input they put on the form and it worked fine, but the same method I think it does not recognize when the same user is signed in the website.
The below code work's when the user sign-up to the website
$user->permissions()->create(UserPermission::user_group($nature_of_entity));
But when I want to use the below method it, I get an error Trying to get property of non-object.
public function hasPermission($permission) {
return (bool) $this->permissions->$permission;
}
public function permissions() {
return $this->hasOne('App\User\UserPermission', 'user_id');
}
In the user database a table named users_permissions that has (id, user_id, is_group_one, is_group_two, is_group_three)
I'm trying to see it the user is in which group, like:
if($app->user->hasPermission('is_group_one')){
echo 'Group One';
}
But I get an error Trying to get property of non-object.
I'd really appreciate it if any can help and if they are ways I could do this and use Laravel Eloquent Relationships methods. I hope you can understand what I mean.
Create a scope that queries through the permissions relationship and checks if the column (i.e. $permission) is TRUE. Axe the (bool) bit...
public function scopeHasPermission($query, $permission)
{
return $query->permissions->where($permission, true);
}
Then in your controller, keep this the same as you had it:
if($app->user->hasPermission('is_group_one')) {
...
}