Reuse user resource route for current user - laravel

I've created a resource route for users.
Route::resource('users', 'UsersController');
My controller handles the path /user/1/edit with in my users controller like so:
public function edit(User $user)
{
$this->authorize('update', $user);
...
The template for this page is: resources/views/users/edit.blade.php.
How would I define a new route, /user/edit, which dynamically passes the current user and reuses the edit(User $user) method while also reusing the same view template?

Your edit() method will need to change to conditionally accept the User model. You then need to check if $user was passed, else assume current user is required:
public function edit(User $user = null)
{
$user = $user ?: auth()->user();
$this->authorize('update', $user);
...
And create the new route:
Route::get('user/edit', 'UsersController#edit')

Try this:
Route::get('users/{user}/edit', 'UserController#edit')->name(edit-user);
Then, pass in the user id in route like this:
route('edit-user', ['user'=>$user->id]);
I hope this helps you.

Related

How to get User()->id in Controllers (Laravel 8+)

I am trying to select tasks by user('id'), but I can't get it in a Controller, where I selecting data from DB.
I have tried many thing and some of them from stackoverflow, but it isn't working.
I tried:
1. $userId = Auth::check() ? Auth::id() : true;
2. Auth::user()->id;
3. public function getUserId(){
on Model} - and then get this value on Controllers
and some other things
I have the simplest code:
I installed registration: npm artisan ui --auth something like that
I installed vuejs (on Laravel)
I created api on Laravel, and some logic on vue
I didn't touch "app.blade.php" it's the same as it was.
I can get data, user: name, id and all what I want in file "app.blade.php" but I need those data in folder->file: App\Http\Controllers{{SomeController}}, but I don't know how.
Was someone in this situation?
How can I get user id in Controllers?
Thanks guys for earlier.
If you need user id, just use one of this :
auth()->id();
using Auth facade's
\Auth::id();
or, using Request instance
$request->user()->id
Follow this simple controller code, i showed 3 different way here :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class SomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function getUserId(Request $request)
{
$user = Auth::user(); // Retrieve the currently authenticated user...
$id = Auth::id(); // Retrieve the currently authenticated user's ID...
$user = $request->user(); // returns an instance of the authenticated user...
$id = $request->user()->id; // Retrieve the currently authenticated user's ID...
$user = auth()->user(); // Retrieve the currently authenticated user...
$id = auth()->id(); // Retrieve the currently authenticated user's ID...
}
}
Auth::user()->id;
This should work if you have Auth middleware on that controller method where you try to get it, please check do you added that middleware.
For checking you can use php arisan route:list command.
Is someone still searching an answer on this question. I have some explanation how can you do this.
Laravel has a Router which routes authorization process through that Controller which you want, so you should redirect that process on your Router and in Controller create constructor which allows you to take user id.
How can you do that?:
1. First of all you should find Controller and Route which responsible for authorization and registration users.
In my case it was:
a)App\Http\Controllers\HomeController
b)routes\web.php
2. Second, you should redirect your authorization Router to the Controller where you trying to get Auth::id();
In my case it was:
App\Http\Controllers\TasksController
so, in routes\web.php I did this:
//was
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
//was
Auth::routes();
//was
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
//added
Auth::routes();
//added
Route::get('/home', [App\Http\Controllers\TasksController::class, 'index'])->name('home');
perhaps you should have index function on that controller
3. Third you should add constructor in your controller where you want to get user id, this constructor I took from HomeController, it already was there.
In my case it was:
public function __construct()
{
$this->middleware('auth');
}
code with function on my TasksController:
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$userId = Auth::check() ? Auth::id() : true;
}
And now I can take user id.
PS: constructor I added on the top in class TasksController in Controller

Custom route for edit method without ID in URL

I want to make a settings screen for my users, and I want the URL to be easy an memorable: domain.com/user/settings
I want this route to point use the UserController#edit method, however, the edit() method requires ID parameter.
Is there someway I can use user/settings URL without specifying the ID in the URL, but still use the same edit() method in the UserController?
The edit URL could be use without any parameter. In that case you can mention the user in controller.
Route
Route::get('user/settings');
Controller
public function edit()
{
$user = Auth::user();
}
Seems like I managed to solve it?
web.php:
Route::get('user/settings', 'UserController#edit')->name('user.settings');
Route::resource('user', 'UserController');
UserController.php:
public function edit(User $user = null)
{
$user = Auth::user();
}

Laravel show() parameter are null

I am using Laravel version 5.6.26. My show() parameter get null value. Why? and how to solve it? Thank you
web.php
Route::get('/peoples', 'UsersController#index')->name('peoples');
Route::get('/peoples/{id?}', 'UsersController#show');
UserController.php
public function show(User $user)
{
$user = User::where('id', $user->id)->first();
//$user = User::find($user->id)->first();
return dd($user);
//return view('profile',['user' => $user]);
}
user.blade.php when I click <a href="/peoples/{{$user->id}}" > , it show null
<h4><a href="/peoples/{{$user->id}}" > {{$user->name}}</a></h4>
result
https://imgur.com/QlaiFse
But if i do like this,I can get the value
public function show(User $user)
{
$user = User::where('id',1)->first();
//$user = User::find($user->id)->first();
return dd($user);
//return view('profile',['user' => $user]);
}
The way you defined your show method i.e. show(User $user) is called route model binding if your variable name ($user) is similar to your route declaration. But your route declaration is /peoples/{id?} so the User instance is not created in your controller. So just rename the route declaration as /peoples/{user?}.
The use case of route model binding is you don't want to query/load the model related to a route parameter. So if you define the route the way I've mentioned you won't need the $user = User::where('id', $user->id)->first(); query. Because Laravel will automatically instantiate that $user with the User model of id passed in the route.
If you want to query/load the User model manually then keep your existing route declaration as it is. And change your controller method declaration as show($id = null)
You are injecting the User model in your controller, but not accessing the route path. If you want to access the {id} which set in the route, you have to access that in your controller too.
So your UserController will be something like
public function show(User $user, $id)
{
$user = User::where('id', $id)->first();
dd($user);
}
When you type hinted in your controller's method show() with User, Laravel will automatically inject that using Service Container.
Your UserController.php's code should be:
public function show(User $user) {
// no need to fetch user again. Laravel had already done that for you.
dd($user);
return view('profile', compact('user'));
}

Error when I try to edit user

I am using Laravel 5.4.18. I am getting this error when I try to edit user
Missing argument 2 for App\Http\Controllers\UsersController::edit()
Here is what I did
https://paste.laravel.io/Pyw5M#18
Change this:
public function edit(User $user, $id)
{
$user = $user->find($id);
return view('admin/users/edit', compact('user'));
}
To this:
public function edit(User $user)
{
return view('admin/users/edit', compact('user'));
}
When you define (User $user) laravel auto-injects the user model, so no need to find the model again based on the id.
In this case i expect your route to look like this:
Route::get('users/{user}/edit', UserController#edit)
Or you can use resource controllers so this is handled for you:
https://laravel.com/docs/5.4/controllers#resource-controllers

Laravel 5 Pass Data from Middleware to Controller

My middleware is similar to Auth. It checks for a URL pattern (eg: /rest/*), and then looks for token in the request, retrieves its corresponding user from database. After that, I want to save that user in a variable so that I can get back to it later in any of the following controller. What's the best way?
Middleware:
public function handle($request, Closure $next)
{
$token = Input::get("token");
// get user data from database
$user = User::get_user_from_token($token);
// ?? -> How to pass $user to controller, so that ..
return $next($request);
}
In Controller:
public function profile_save() {
// I get the user back here without querying again
$user = ???
}
I would flash the data to the session. When you flash data it only stays there until the next request.
In your middleware add
Session::flash('user', $user);
Don't forget to add this at the top of your middle ware
use Session;
Then whenever you need to access your user use
Session::get('user');
Here is a link to the docs for reference
http://laravel.com/docs/5.0/session#flash-data
I'm using Laravel 5.1.
To pass parameters from the middleware to the controller you can add it to the Request object.
In the middleware:
public function handle($request, Closure $next)
{
$user = 'DB Call To Get User';
$age = 20;
$request->route()->setParameter('user', $user);
$request->route()->setParameter('age', $age);
return $next($request);
}
Then you can get the user in the controller from either the arguments:
public function TestAction(Request $request, User $user, $age)
{}
Or explicitly from the request object:
public function TestAction(Request $request)
{
$user = $request->route()->getParameter('user');
$age = $request->route()->getParameter('age');
}
Of course you can flash the data temporarily to the session or save it to the session itself and set an expiry time, but if you only need it to last for the lifetime of the request then i think this is a good way.
Hope this helps!

Resources