I am Having this error in my code
Undefined function 'App\Http\Controllers\api\createToken'.intelephense(1010)
i have done all the necessary imports needed to use passport so that i can generate apiTokens but it does not work for me
i will really appreciate it if i can get some one to help me in fixing this error thanks in advance
<?php
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class authController extends Controller
{
public function signup(Request $request)
{
//
$rules=[
'name'=>'required|max:55',
'email'=>'required|email|unique:users',
'password'=>'required',
// 'password_confirm'=>'required',
];
// $valid = $request->validate($rules);
$valid = Validator::make($request->all(),$rules);
if($valid->fails()){
return response()->json(
$valid->errors(),400
);
}else{
$user = User::create($request->all());
$accessToken = $user-createToken('authToken')->accessToken;
return response()->json(['user'=>$user,'accessToken'=>$accessToken], 201);
}
}
public function login()
{
//
}
public function logout(Request $request)
{
//
}
public function user(Request $request)
{
$request->user()->token()->revoke(); return response()->json([
'message' => 'Successfully logged out'
]);
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
Sorry Guys it was a typo in the code
$user-createToken('authToken')->accessToken;
i left out the '>' character
$user->createToken('authToken')->accessToken;
Related
I'm having the following error when I try to check a permission using policies:
Too few arguments to function App\Policies\AnswerPolicy::view(), 1 passed in /Users/georgio/Projects/Laravel/municipality-app/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php on line 710 and exactly 2 expected (View: /Users/georgio/Projects/Laravel/municipality-app/resources/views/layouts/loggedin.blade.php)
AnswerPolicy
<?php
namespace App\Policies;
use App\Answer;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class AnswerPolicy
{
use HandlesAuthorization;
public function view(User $user, Answer $answer)
{
return true;
}
public function edit(User $user)
{
return true;
}
public function create(User $user)
{
return true;
}
public function delete(User $user)
{
return true;
}
public function update(User $user)
{
return true;
}
}
AnswersController
<?php
namespace App\Http\Controllers;
use App\Question;
use App\Answer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AnswersController extends Controller
{
public function index()
{
$this->authorize('view');
return view('answers.show')->with('questions', Question::all());
}
public function create($questionId)
{
$this->authorize('view-submit-answer');
return view('answers.create')->with('question',Question::find($questionId));
}
public function store()
{
$this->authorize('');
$this->validate(request(),[
'answer' => 'required',
]);
$data = request()->all();
$answer = new Answer();
$answer->answer = $data['answer'];
$answer->question_id = $data['question_id'];
$answer->user_id = Auth::id();
$answer->save();
return redirect('/questions/answers');
}
public function edit($answerId)
{ $this->authorize('view-edit-answer');
return view('answers.edit')->with('answer', Answer::find($answerId));
}
public function update($answerId)
{
$this->validate(request(),[
'answer' => 'required',
]);
$data = request()->all();
$answer = Answer::find($answerId);
$answer->answer = $data['answer'];
$answer->save();
return redirect('/answers-question');
}
public function destroy($questionID)
{
$this->authorize('delete-answer');
$answer = Answer::where('question_id', $questionID)->where('user_id', Auth()->id());
$answer->delete();
return redirect('/questions/answers');
}
}
loggedin.blade.php
This is only the part of my code that is causing the error
#can('view', App\Answer::class)
<li>
<a href="/questions/answers">
<span><i class="fa fa-pencil"></i></span>
<span>Answer Question</span>
</a>
</li>
#endcan
I even tried replacing $answer with App\Answer::class and I still had the exact same error.
You can check the full error stack at:
https://flareapp.io/share/xPQQQXP1#F66
The documentation says
When defining policy methods that will not receive a model instance, such as a create method, it will not receive a model instance. Instead, you should define the method as only expecting the authenticated user
I don't see an Answer instance inside your #can statement there. Does one exist? If so, you should be doing this:
#can('view', $answer)
Or, if one doesn't exist at that point, define your method like this
public function view(User $user)
And call it like this:
#can('view', \App\Answer::class)
I am trying to add a if condition when resource auto generates.
When I run php artisan make:controller SomeController -r, I want to generate the following,
class SomeController extends Controller
{
public function index()
{
if (Auth::user()->can('')){
//
}else{
//
}
}
public function create()
{
if (Auth::user()->can('')){
//
}else{
//
}
}
public function store(Request $request)
{
if (Auth::user()->can('')){
//
}else{
//
}
}
public function show($id)
{
if (Auth::user()->can('')){
//
}else{
//
}
}
public function edit($id)
{
if (Auth::user()->can('')){
//
}else{
//
}
}
public function update(Request $request, $id)
{
if (Auth::user()->can('')){
//
}else{
//
}
}
public function destroy($id)
{
if (Auth::user()->can('')){
//
}else{
//
}
}
}
Try to use middleware to do this,
See: https://laravel.com/docs/master/middleware
namespace App\Http\Middleware;
use Auth;
use Closure;
class AuthCan {
public function handle($request, Closure $next)
{
if (Auth::user()->can('')){
//
return $next($request);
}else{
//
return response()->json(['status' => false, 'code' => 1001, 'msg' => 'Cannot ...']);
}
}
}
Defined your route Middleware in app/Http/Kernel.php:
protected $routeMiddleware = [
'AuthCan' => \App\Http\Middleware\AuthCan::class,
...
And use middleware in route.
Route::group(['middleware' => 'AuthCan'], function(){
Route::get('/', 'SomeController#index');
Route::get('/{id}', 'SomeController#show');
...
}
We know that laravel has an update () method that updates records using the http "put" method. But I do not know how to create an edpoint in which I will be able to modify the email.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
public function index()
{
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
}
public function store(Request $request)
{
$user = new User();
$user->name = $request->get("name");
$user->email = $request->get("email");
$user->password = $request->get("password");
$user->save();
return response()->json($user->toArray(), 200);
}
public function show($id)
{
//
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
And my route:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('v1/users/create', 'UserController#store');
RESTful APIs made by me tests in Postman. Help me somebody
Looking at your question, I think you need to create a route to link to update method in your controller same way you created a post for creating user.
Route::put('v1/users/client/{id}', 'UserController#update);
OR you can use laravel predefined code to create all CRUD routes.
Route::resource('v1/users/client', 'UserController').
To view all the routes created, use
php artisan route:list
Have a further study on this.
I was able to login and get user token using JWT in laravel.However, while tring to get authenticated user (getAuthUser) by passing that token, I get following error:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'where
clause' (SQL: select * from user where `` = 12 limit 1)"
AuthenticationController:
<?php
namespace Modules\Authentication\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use JWTAuth;
use JWTAuthException;
use Modules\Settings\Entities\Users;
use Modules\Authentication\Http\Requests\Authentication;
class AuthenticationController extends Controller
{
public function __construct()
{
// $this->user = new Users;
$this->guard = \Auth::guard('api');
}
public function login(Authentication $request){
$credentials = $request->only('username', 'password');
try {
// verify the credentials and create a token for the user
$token = JWTAuth::attempt($credentials);
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token'], 500);
}
// if no errors are encountered we can return a JWT
return response()->json(compact('token'));
}
public function getAuthUser(Request $request){
$user = JWTAuth::user($request->token);
// dd($user);
return response()->json(['result' => $user]);
}
}
Users Model:
namespace Modules\Settings\Entities;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class Users extends Model implements JWTSubject,Authenticatable{
Protected $table="user";
// protected $primaryKey = 'id';
protected $fillable = ['id','username','password','user_status_type_id','client_id','created_userid'];
protected $hidden = [
'password', 'remember_token',
];
public function user_status(){
return $this->belongsTo('Modules\Settings\Entities\UserStatusType','user_status_type_id');
}
public function user_client(){
return $this->belongsTo('Modules\Settings\Entities\Client','client_id');
}
public function role()
{
return $this->belongsToMany('Modules\Settings\Entities\Role','user_role','user_id','role_type_id');
}
public function getAuthPassword() {
return $this->password;
}
public function getJWTIdentifier() {
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
public function getAuthIdentifierName(){}
public function getAuthIdentifier(){}
// public function getAuthPassword(){}
public function getRememberToken(){}
public function setRememberToken($value){}
public function getRememberTokenName(){}
}
Route:
Route::group(['middleware' => 'web', 'prefix' => 'api/v1/authentication', 'namespace' => 'Modules\Authentication\Http\Controllers'], function(){
Route::post('auth/login', 'AuthenticationController#login');
// Route::group(['middleware' => 'jwt.auth'], function () {
Route::get('user', 'AuthenticationController#getAuthUser');
// });
});
I am testing it in postman by
GET: ..../api/v1/authentication/user?token={Token}
EDIT:
Now my method for getAuthUser in the controller looks like this:
public function getAuthUser(Request $request){
// $token = JWTAuth::getToken();
// dd($token);
$input = $request->all();
JWTAuth::setToken($input['token']);
// dd($input['token']);
$user = JWTAuth::toUser($input['token']);
// dd($user);
return response()->json(['result' => $user]);
}
and In JWTAuth.php
public function authenticate()
{
// dd($this->getPayload()->get('sub'));
$id = $this->getPayload()->get('sub');
// dd($id);
// dd($this->auth->byId($id));
if (! $this->auth->byId($id)) {
return false;
}
return $this->user();
}
here by doing dd($id), value of id comes but if I try to do dd($this->auth->byId($id)) I get the same error as before.
Try this to retrieve the user instead:
public function getAuthUser()
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
// the token is valid and we have found the user via the sub claim
return response()->json(['result' => $user]);
}
Taken from docs, Retreiving the Authenticated user from a token
EDIT:
May not make a difference but just looking at your Model again and I would say that it needs to be
class Users extends Authenticatable implements JWTSubject
rather than
class Users extends Model implements JWTSubject,Authenticatable
I'm trying Laravel 5.4 (i usually work with 5.1) and im actually copypasting most of the code, so i dont understand what is the trouble, maybe is because there is a better way to do it but yeah, its been 1 hour and i cant get past this;
Hope you can help me with this..
In case this isn't enough i'll be posting my views and routes. Thank to everyone.
This is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = ['user_id', 'user_name', 'user_birthday'];
public static $rules = [
'user_name' => 'required|max:255',
'user_birthday' => 'required'
];
public $timestamps = false;
}
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UsersController extends Controller
{
public function index()
{
$users = User::with('user_id')->orderBy('user_id', 'ASC')->paginate(10);
return view('admin.users.index')->with("user", $users);
}
public function create()
{
return view('admin.users.create');
}
public function store(Request $request)
{
$users = new User($request->all());
$users->save();
return redirect()->route('admin.users.index');
}
public function show($id)
{
$users = User::find($id);
}
public function edit($id)
{
$users = User::find($id);
return view('admin.users.edit')->with('user', $user);
}
public function update(Request $request, $id)
{
$users = User::find($id);
$users->user_name = $request->user_name;
$users->user_birthday = $request->user_birthday;
$users->save();
return redirect()->route('admin.users.index');
}
public function destroy($id)
{
$users = User::find($id);
$users->delete();
return redirect()->route('admin.users.index');
}
}
Your error is from the following line of code. When you use with on a model is to load children relationships or sub-models. That is why the application is looking for the relationship user_id in the User Model thinking that it's a sub-model of the User model but it's not, so it return an error.
wrong
$users = User::with('user_id')->orderBy('user_id', 'ASC')->paginate(10);
correct
$users = User::orderBy('user_id', 'ASC')->paginate(10);