I have a site where an admin can register themselves. Currently there is only one admin so the functions below works for passing the value:
public function getAllVideos()
{
$videos = Video::all();
$price = DB::table('donor')->sum('amount_donated');
$goal = auth()->user()->goal;
return view('adminmanagement', compact('videos', 'price', 'goal'));
}
public function changeGoal(Request $data)
{
auth()->user()->update([
'goal' => $data->input('newGoal')
]);
return redirect('/home');
}
And if I need to just pass it to a view where a normal user can see,
do I do the following?
public function getAllVideos()
{
$videos = Video::all();
$price = DB::table('donor')->sum('amount_donated');
User::first()->goal;
return view('adminmanagement', compact('videos', 'price', 'goal'));
}
public function changeGoal(Request $data)
{
auth()->user()->update([
'goal' => $data->input('newGoal')
]);
return redirect('/normalview');
}
But what if there are more than one registered users (admin) in the system. Would it still be fine as only one admin is logged in at a time? Or does the code need to change?
EDIT:
I have registration only for admins (which are 'user'), the normal users ( which are 'donors' in my case) don't have any registration/logging needed. So my main purpose is to be able to pass that $goal value to two different pages. One accessbile to admin(let's say a registered and logged in admin named jon), and other accessible to the normal user. so my current code 'User::first()->goal;' should do the trick, right? but, will it be fine if lets say, another admin named jim registers and logs in. So now the admin that is logged in is jim, not jon will it still display the $goal value in the admin's view page(accessed by jim) and normal user's view page(accessed by a normal/random person)?
From your other question you said that there's only one user and it's an admin. In that case you could replace the auth()->user() with User::first(). But if you have more than one admin or users, you need to specify the user using User::find(1) with the user id. Every user has a goal field and i assume you want to fetch only the goal from the admin user with the actual value. If so you can do this.
Replace
$goal = auth()->user()->goal;
With
$goal = User::find(1)->goal;
Make sure to use the user id of the user with the goal value.
retrieving user via auth()->user() Or Auth::user()(I prefer the second way) only return the current logged user.
If you write :
Auth::user()->username it will display their own name to all user viewing this page.
No need to worry :)
However, User::first() will get the first reccord in the users table so it will always be the same user and it may be a normal user
Related
I am trying to make a global variable in AppServiceProvider.php that I will need throught my whole application meaning in all blade files. This variable is $profile which gets the profile data from user and displays them in blades. I made it so when I am on my profile it shows authenticated user which is me and it is fine (in url is like this profile/Authuser), that Authuser is username from database. Problem is when I go to some other profile then I get error undefined username (in url profile/Someuser). I need help on to get that username in AppServiceProvider.php. Problem is in that $username in service provider. I don't know how to pass it in there globally. Any help is appreciated. Here is my code.
AppServiceProvider.php
public function boot()
{
$profileId = $this->getIdFromUsername($username); // Here is problem, I don't know how to get that username
view()->composer('*', function ($view) {
$view->with('profile', Auth::id() ? UserProfile::profileDetails($profileId, Auth::user()->id) : []);
});
Builder::defaultStringLength(191); // Update defaultStringLength
}
public function getIdFromUsername($username)
{
if ($user = User::where('username', $username)->first()) {
return $user->id;
}
return abort(404);
}
web.php
Route::get('profile/{profile}', 'UserProfileController#showProfile')->name('profile.show');
I believe you are over complicating yourself.
If I understand your app. A user has a Profile correct?
Go to your User Model and create a relation between User and Profile
public function userProfile()
{
return $this->hasOne('App\UserProfile');
}
With that, the profile will follow the user, and you don't need to be passing it around.
If you want the Profile for the current User.
Auth::user()->userProfile();
If you want the profile of another user then
$owner = User::where('username', $username)->first();
$owner->userProfile();
Basically you can have access to the profile of your logged in user, or any other user easily by just finding the user you want.
Now, if you really wish to have a Model in every view, you are placing it in the wrong place. You see, Service Providers are intended to tie things up, not to get data. What you are probably thinking about is a View Composer that you do tie in with a Service Provider, but the actual data comes from the Composer itself. You can learn more about View Composer in the Docs. https://laravel.com/docs/7.x/views#view-composers
View Composers are just one way of doing it, a quick google search brought up this question which offers 3 additional alternatives to the view composer.
How to pass data to all views in Laravel 5?
Hope that helps.
When my user registers successfully in the website, He will be redirected to his profile page like this:- domain.com/u/{username} , So how do I know that the profile view has been loaded/viewed by the user for the first time, So I can but some guidance in his profile to let him know how to edit or use some functionalities in his profile?
Thanks in advance.
This is the way I handle it:
Add a column to your user table called profile_viewed that is of type integer, defaut(0);
$table->integer('profile_viewed')->default(0);
In your controller method set that value to 1 when you render the view:
public function profile(User $user)
{
$user->profile_viewed = 1;
$user->save();
//logic to render the view
}
I am attempting to introduce "ghosting" into my application - wherein I can access our app from the POV of a user.
Currently using the loginUsingID function to achieve this, with a protected route only accessible by admins. However, I would also like to display to the admin that they are ghosting a user by displaying a bar across the top of our app.
I was thinking of adding a property to the user is_being_ghosted - setting it as false on logout, false on login, and true on ghostLogin.
But I realize there is a small chance an admin attempts to ghost a user, and it sets that property, and while they are investigating things within the account, the user themselves refreshes their page (they were already authenticated so do not need to login again). In that case they would see this "admin bar" across the top, which clearly I wouldn't want to happen.
Is there an efficient way to achieve what I'm trying to do here? Am I going about this the wrong way?
As jszobody has mentioned. You could rather manage the state inside the session. You secure the /ghost route and then if the original-user-id session is set you display your bar and an unghost link.
public function ghost(Request $request, $id)
{
$request->session()->put('original-user-id', Auth::user()->id);
Auth::loginUsingId($id);
return redirect('/');
}
public function unghost(Request $request)
{
if ($request->session()->has('original-user-id')) {
Auth::loginUsingId($request->session()->pull('original-user-id'));
}
return redirect('/');
}
Update:
The ghost endpoint basically accepts the id that you want to impersonate, typically found through an ajax search input or something similar. Whatever suites your use case.
I have a Laravel web application consist of 2 types of user:
customer
admin
Base on their user type , they can see, and perform different things.
Customer
When log-in as customer, my customer will see different dashboard.
Admin
When log-in as admin, I can see a list of users in a table
Example,
userA
userB
userC
more …
Goal:
I want to see what customer see when click on one of the user on the list.
I couldn’t come up the solution for that.
IMO
Will Auth::user()->type work for this scenario ?
The goal is to render the page as Auth:user()->type == ‘customer’, when the actual Auth::user()->type == ‘admin’. I'm not entirely sure if what I am trying to do is possible.
How would I do something like that in Laravel ?
You could try what I did in one of my projects - implementation is pretty simple, maybe you can make use of that as well.
There is additional action in our AuthController that allows a user to switch to other users and remembers current user ID in session:
public function switchUser($userId)
{
// disallow switched users from switching again
if (Session::get('previous_user')) App::abort(403);
$user = User::findOrFail($userId);
Session::set('previous_user', Auth::id());
Auth::login($user);
return redirect('some path');
}
Second part is customized logout function, that for switched users switches them back to their original user account instead of logging out:
public function getLogout()
{
if ($previousUser = Session::get('previous_user')) {
Session::remove('previous_user');
Auth::loginUsingId($previousUser);
return redirect('some path');
}
Auth::logout();
return redirect('some path');
}
With that logic you'll be able to switch to other users and back. You might need to add permission checking, so that only admins can do that etc., link the customers in the list to the switch URL, anyway the core of the functionality is there in the code above.
I'm speaking about a simple laravel's 4.2 web site with authentication system.
I am user A (super-user), and I want to see if user B or/and user C (and all other users) are logged in. Is there any built in function (something with Auth class) to do this ?
You can't say for sure if a user B/C is logged in. But you can guess if a user is logged in. If you remember the last action of user B/C and you know the timeout until a user gets logged out automatically this would give you an estimate value if the user is still logged in or not.
Add a migration for your users table and add a new field to your table
$table->timestamp('last_activity')->nullable();
Add a before filter
App::before(function ($request) {
if (Auth::user()) {
$user = Auth::user();
$now = new DateTime();
$user->last_activity = $now->getTimestamp();
$user->save();
}
});
Now you can check when the last action of user B/C was and if this is within the auto logout time it is possible that the user is still logged in. If not the user is definitely logged out.
In case you want to log users activity there is a package Regulus343/ActivityLog.
It's easy but you can only check one person at time which means it's not possible to use complex conditions for example count all logged in users.
If you want to check if a user other than you is logged in, use a helper function like this.
<?php
// Helper.php
public function isLoggedIn($user_id)
{
if(Auth::check())
{
return $user_id == Auth::user()->id;
}
}
?>