Laravel using user id in route - laravel

So I have a route profile/{user_id}
How do I redirect user to that URL when they click on link?
Here's my controller:
{
function checkid($user_id) {
if (Auth::check())
{
$user_id = Auth::id();
return view('profile', [
'id' => $user_id
]);
}
}
}

Bit confused with the question but Laravel uses ID as default for dependency injection and changing it is easy: just change the routeKey in the model BUT in your instance, you're using the signed in user. So forgot the id!
<?php
namespace App\Http\Controllers;
class RandomController extends Controller {
public function index()
{
return view('profile');//use auth facade in blade.
}
}
In your routes use a middleware to prevent none authenticated users from reaching this method
<?php
Route::group('/loggedin', [
'middleware' => 'auth',
], function() {
Route::get('/profile', 'RandomController#index')->name('profile.index');
});
Now to redirect in your blade file use the route function, don't forget to clear your cache if you've cached your routes!
<h1>Hi! {{Auth::user()->name}}</h1>
View profile
Because I used the name method on the Route I can pass that route name into the route function. Using php artisan route:list will list all your route parameters which is cool because it will also tell you the names and middlewares etc.
if I had a route which required a parameter; the route function accepts an array of params as the second parameter. route('profile.index', ['I_am_a_fake_param' => $user->id,]).
Let me know if you need help with anything else.

You can redirect with the redirect() helper method like this:
return redirect()->url('/profile/' . $user_id);
But I'm not really following your usecase? Why do you want to redirect? Do you always want the user to go to their own profile? Because right now you are using the id from the authenticated user, so the user_id parameter is pretty much useless.

Related

Laravel edit route for basic CRUD application giving 404

I'm trying to set up a basic Laravel 9 CRUD application, and I cannot get the edit route working for the User Controller.
routes/web.php
Route::get('/dashboard', function () { return view('dashboard'); })
->middleware(['auth'])->name('dashboard');
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{$id}/edit','edit')->middleware('auth');
Route::post('user/{$id}/edit','update')->middleware('auth');
Route::get('user/{$id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
require __DIR__.'/auth.php';
UserController.php
class UserController extends Controller
{
function edit(int $id)
{
echo 123;
}
I'm getting a 404 NOT FOUND page
Also, why don't I see the stack trace for this error?
Also, in some examples, I've seen people using the model class name as the parameter type in the controller method declaration, such as:
function edit(User $id)
{
echo 123;
}
However, I've also seen other examples using int instead. So which is the correct one?
First, inside your .env filte you should put
APP_ENV=local
APP_DEBUG=true
and change your web.php to:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth'])->name('dashboard');
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{id}/edit','edit')->middleware('auth');
Route::post('user/{id}/edit','update')->middleware('auth');
Route::get('user/{id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
require __DIR__.'/auth.php';
Then, try to run
php artisan route:list
and check if your routes are correct.
And try to remove middlewares inside user files, maybe you do not have login page and it redirects you there.
Be sure you are in the correct url like localhost/user/1/edit
Parameters in routes don't take a starting $. Change all occurrences of {$id} in your routes to just {id}:
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{id}/edit','edit')->middleware('auth');
Route::post('user/{id}/edit','update')->middleware('auth');
Route::get('user/{id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
More on Route Parameters
Edit: you might also want to take a look at Resource Controllers. Something like Route::resource('users', UserController::class); will manage all of the required routes

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

Laravel Passport post route test on postman

I set up Laravel Passport and started to create a few Get routes to get some data, that worked fine.
Now I am trying to post to get on auth token, which currently does not work:
This is my route which I call (Get route works, Post route does not work):
Route::group(['middleware' => 'auth:api'], function ()
{;
Route::get('users', ['as' => 'users', 'uses' => 'ApiController#users']);
Route::post('login/{id}/{name}', ['as' => 'login', 'uses' => 'ApiController#login']);
});
The method in my ApiController looks currently like this:
public function login(Request $request, $id, $name)
{
if($request->isMethod('post'))
{
$id = $request->id;
$name = $request->name;
$inquiry = new Inquiry();
$inquiry->user_id = $id;
$inquiry->user_name = $name;
if($inquiry->save())
{
return redirect()->route('inquiry.index')->with('success', 'Success.');
}
else
{
return redirect()->route('inquiry.index')->with('error', 'An error accured.')->withInput();
}
}
else
{
dd("Use Post.");
}
}
I tried to call it with following options:
Edit
I somehow managed to get this work after many hours, but still dont understand something.
First I did following:
public function callback(Request $request)
{
dd($request->code) // this holds a token I need for the code parameter in the post
...
With that I could get the token for the code parameter, but I think there is a better way to do that.
And finally this is now how I get the access + refresh token:
But there has to be a better way to get the code token of the callback request ($request->code), instead of dumping it and copying it.
The problem is that you have your login route inside a route group with auth:api on it. This means the user needs to be authenticated to even be able to authenticate. Just remove the login route outside the group and you should be fine.
You should call the Passport::routes method within the boot method of your AuthServiceProvider. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
/oauth/authorize route is already defined by the Passport::routes method. You do not need to manually define this route.

Set username as prefix in URIs Laravel

I want to set prefix in all of the authenticated URIs in Laravel 5.3 app. If I use Route::group(['prefix' => {username}]), then how can I get the username in web.php file.
Assuming you have defined routes like this:
Route::group(['prefix' => '/{user}'], function() {
Route::get('/profile', 'UserController#showProfile')->name('user.profile');
});
You can use Laravel's route-model binding to pass an User instance directly into your routes:
View Profile
Then in the controller , you can easily grab that model instance:
class UserController extends Controller
{
public function showProfile(User $user)
{
return view('user.profile.index', compact('user'));
}
}
Check out the documentation here.
EDIT: By default, Laravel uses the id column when retrieving a given model class. You can change that to any column, in your case username , easily by overriding the getRouteKeyName() method on your User model.
public function getRouteKeyName()
{
return 'username';
}
You can't and you shouldn't hardcore routes with usernames. If you have 100 users, do you plan to create 100 route groups for each user? Assuming each user has 2 routes that's 200 routes.
What you need to do is generate routes with username segment and detect the user on the fly based on the user name.
Route::group(['prefix' => '{username}'], function () {
Route::get('profile', 'UserController#profile');
Route::get('setting', 'UserController#setting');
});
The routes generated would be like
http://example.app/{username}/profile
http://example.app/{username}/setting
So a user with username adam with get the links.
http://example.app/adam/profile
http://example.app/adam/setting
Similarly you can have username based links for all your users and you need to detect them in your controller using route model binding or the standard way.
Edit
For closure based routes you can get the url segment like so
Route::get('{username}/profile', function ($username) {
return 'Username is '.$username;
});
With controllers you get them as the parameters.
public function profile($username)
{
return $username;
}

Laravel default Auth::routes() inside of group prefix

I'm attempting to create a prefix with a variable for "companies" to login to the platform. All users are tied to a company so the normal /login isn't desired. I'd like to use something like `/acme-company-name/login
I am using the default Laravel auth via: php artisan make:auth on a fresh install.
Route::group(['prefix' => '{company}'], function () {
Auth::routes();
});
When I try navigating to /company-name/login I see the following error:
Missing required parameters for [Route: login] [URI: {company}/login].
Looking inside the auto-generated login.blade.php I see the function call route('login') and this seems to be where everything is breaking. I think I need some way to supply a variable to that function or redefine what the "login" route is in some fashion ? I'd rather not have to replace the call Auth::routes() but will certainly do so if that is required to fix this issue.
I should note, i've tried defining the group 'as' => 'company' and changing route('company.login') but then I am told the route company.login is not defined.
Can you try by passing $company variable to the function as well?
Route::group(['prefix' => '{company}'], function ($company) {
Auth::routes();
});
And make sure you pass the company-name when calling the route as it's a required parameter.
In login.blade.php use {{ url("$company/login") }} instead of route('login').
route() helper has more than one parameter ;)
route('login', ['company' => $company])
you need to share your prefix in your views and set route as the following:
Route::group(['prefix' => '{company}'], function ($company) {
view()->share('company', $company); // share $company in views
Auth::routes();
});
now you have $company which is instance of Router and you need access to route prefix value for this you need get current route and get company parameter so you should rewrite your route() helper function as the following:
{{ route('login',['company'=>$company->getCurrentRoute()->__get('company')]) }}
// getCurrentRoute Get the currently dispatched route instance
//__get Dynamically access route parameters
EDIT:
you can write custom helper function as the following:
/**
* Generate the URL to a named route for Company Auth.
*
* #param string $name
* #param Router $company
* #return string
*/
function companyRoute($name,$company)
{
return app('url')->route($name, ['company'=>$company->getCurrentRoute()->__get('company')] ,true);
}
Please check the code that is working fine for me.
Route::group(['prefix' => '/{company}'], function () {
// ensure that auth controllers exists in right place (here it is App\Http\Controllers\Auth\LoginController)
// in LoginController funtion
Auth::routes();
//or you can try using custom routing like this
Route::get('{something}', function($company, $something)
{
var_dump($company, $something);
});
});
If you define this route at the end of the file then the error that you have mentioned we face.
ErrorException in UrlGenerationException.php line 17:
Missing required parameters for [Route: login] [URI: {company}/login]. (View: \resources\views\auth\login.blade.php)
Try with defining this route as first route in web.php and check.
Thanks
Looking inside the auto-generated login.blade.php I see the function call route('login') and this seems to be where everything is breaking.
Yes. By doing
Route::group(['prefix' => '{company}'], function () {
Auth::routes();
});
you are making all auth routes take a company parameter. So, in your views, instead of route('login'), you can do route('login', ['company' => Request::route('company')]). (And the same for all auth routes).
Then probably in your App\Http\Controllers\Auth\LoginController you will need to override the login method accordingly:
public function login(Request $request, $company)
{
// you can copy some behaviour from
// https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php#L28
}

Resources