Laravel Auth return null - laravel

I'm using 2 routes, one for loginUsingId(1), and the second one for test if user is logged.
When try to see Auth::id(), it is ever null.
//My Routes
Route::get('/login', [\App\Http\Controllers\UserController::class,'login']);
Route::get('/test_login', [\App\Http\Controllers\UserController::class, 'getUser']);
This are the methods in UserController
namespace App\Http\Controllers;
use App\Http\Middleware\Authenticate;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
public function login()
{
$auth = Auth::loginUsingId(3);
return var_dump($auth); // <--- here return 3
}
public function getUser()
{
return response(['user'=>Auth::id()]);
}

you need to apply middleware to work Auth::user()
Route::get('/test_login', [\App\Http\Controllers\UserController::class, 'getUser'])->middleware('auth');
then try

If you don't want to use the default Auth middleware it's not gonna work.
Although, remember there is the
auth()->user()
method that you can try instead ; it's more convenient as you don't need to import any model to use it.

Related

Return value must be of type Laravel 10

I am working on a Laravel 10 project and trying to create a controller that displays records. However, I have run into a problem while attempting to do so :
App\Http\Controllers\StudentController::index(): Return value must be of type Illuminate\Http\Response, Illuminate\View\View returned
I have attached below what I have tried so far:
Student Controller
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Models\Student;
class StudentController extends Controller
{
public function index(): Response
{
$students = Student::all();
return view ('students.index')->with('students', $students);
}
If I remove the Response class, the code works, but I need to implement the Laravel 10 standard. I am unsure how to solve this issue. Can you please provide a solution?
Routes
Route::resource("/student", StudentController::class);
Laravel utilized all of the type-hinting features available in PHP at the time. However, many new features have been added to PHP in the subsequent years, including additional primitive type-hints, return types, and union types.
Release notes.
If you are using view function, you need to use the Illuminate\View\View class for type-hinting.
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use App\Models\Student;
class StudentController extends Controller
{
public function index(): View
{
$students = Student::all();
return view('students.index')
->with('students', $students);
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Models\CatalogueModel;
use Illuminate\Contracts\View\View;
class StudentController extends Controller
{
public function index(): View
{
$data['students'] = Student::all();
return view('students.index')->with($data);
}
}

Laravel test Passport::actingAs($user) use routes?

I have custom passport user login validation (i made it following this) so i make my custom /oauth/token with this route:
/routes/auth.php
Route::post('/oauth/token', [
'uses' => 'Auth\CustomAccessTokenController#issueUserToken'
]);
/app/controllers/auth/CustomAccessTokenController.php
namespace App\Http\Controllers\Auth;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Psr\Http\Message\ServerRequestInterface;
class CustomAccessTokenController extends Controller
{
public function issueUserToken(ServerRequestInterface $request)
{
$httpRequest = request();
if ($httpRequest->grant_type == 'password') {
$user = User::where('email', $httpRequest->username)->first();
return $this->issueToken($request);
}
}
}
If i make a manual POST request to domain.com/oauth/token is correctly handled by the custom controller but when i use Passport::actingAs($user); in a phpunit test not. This Passport::actingAs(); use the routes or have other way to get the authentication token?
You should be able to get the authentication token using
$this->actingAs($user, 'api');

Laravel controller / store

I am new to laravel, i am trying to store a tweet to database and i need to insert user id, but this gives me an error
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Tweet;
class TweetController extends Controller
{
public function store(Request $request){
return Tweet::create([ 'tweet' => request('tweet'), 'user_id' => Auth::id()]);
}
}
error i recive:
App\Http\Controllers\Auth' not found in file
/Applications/AMPPS/www/Twitter/Twitter/app/Http/Controllers/TweetController.php
Any idea?
Yes, you are missing the import, that's why it tries to find it in the Controller location, so put
use Illuminate\Support\Facades\Auth;
// or
use Auth; // you must have the Auth alias in the config/app.php array
as an import, or use the helper function auth()->id() instead.
So instead of mass-assigning the user, you can do the following, in your User model add this:
public function tweets()
{
return $this->hasMany(Tweet::class);
}
Then in your controller just do this:
auth()->user()->tweets()->create([ 'tweet' => request('tweet') ]);
You can use auth() helper to get user id:
auth()->user()->id

Laravel 5 - Can't route to controller

I'm having an issue routing in laravel 5. My code is:
<?php
Route::get('/', function () {
return "Ok";
});
//Authentication Routes
Route::post("/authenticate", "AuthenticationController#Authenticate");
Route::post("/register", "AuthenticationController#Register");
If i place the inline functions, it all works well, however when I try the controller way, it just outputs a blank page.
Any ideas?
Edit: Here's the controller
<?php
namespace App\Http\Controllers;
use User;
use Auth;
use Input;
use Hash;
use Illuminate\Routing\Controller as BaseController;
class AuthenticationController extends BaseController
{
public function Authenticate() {
if(Auth::attempt([ 'email'=>Input::get('email'),
'password'=>Input::get('password')]))
{
return response()->json("OK");
}
else
{
return response()->json("ERROR");
}
}
public function Register() {
return response()->json("Not Implemented");
}
}
You're extending the wrong Controller here:
use Illuminate\Routing\Controller as BaseController;
Also set in your .env file debug=true to see what the Error is.
Probably is controller related issue.
You should extend the Controller within your app\Http\Controllers\ folder. (which falls within the same namespace). Especially to get ValidatesRequests trait working (really useful!).
Fix your controller by removing the:
use Illuminate\Routing\Controller as BaseController;
Example:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Hash;
class AuthenticationController extends Controller
{
public function Authenticate() {
if(Auth::attempt([ 'email'=>Input::get('email'),
'password'=>Input::get('password')]))
{
return response()->json("OK");
}
else
{
return response()->json("ERROR");
}
}
public function Register() {
return response()->json("Not Implemented");
}
}
I know the question has already been answered and accepted, but I thought it a good idea to share something else and I cannot comment yet.
The unresponsive controller can also be caused when adding extra methods inside a resource controller, now there's not a problem in doing that, however.
If adding routes to your route file and you have a resource route setup for that controller, make sure you either:
A: Add the extra routes above the declaration of your resource route.
B: Use a two stroke approach i.e. task/ajax/getGoodStuff
This is because is you do a php artisan route:list you will notice your resource routes have (using the task controller as example):
task/{task} three time for methods head, patch and delete and
task/{task}/edit for editing a record.
Now this will only drive you crazy while the other methods are not completed, but it will drive you crazy at some point!

Routing in Laravel is not working

I am using laravel 5.0
I am trying to route the following. But it is not working
Route::post('accesscontrols/permissions', 'AccescontrolsController#permission');
I don't know what error in this.
It does not access permissions function in AccesscontrolsController
I have a function in AccesscontrolsController
public function permission()
{
$roles = DB::table('roles')->get();
$permissions = DB::table('permissions')->get();
return view('accesscontrols.permission', compact('roles', 'permissions'));
}
What I have did wrong?
Your route declaration should be made in app/Http/routes.php.
Also, make sure that your controller is within the App\Http\Controllers namespace and that it extends App\Http\Controllers\Controller.
Ex:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function permission()
{
...
Also, if you whish to test it in the browser (by typing "accesscontrols/permissions" in the address bar), you route should answer to the GET verb. Try to declare it using Route::get( instead.
You are returning a view in your method and you are not working with any POST data, which is strange. Are you sure you want POST request and not GET?

Resources