Profile page for logged user - laravel 5.2 - laravel

The problem is, when i submit the form, the browser throw MethodNotAllowedHttpException in RouteCollection.php line 219:
My route
Route::group(['middleware' => ['web']], function () {
Route::resource('dash/reports', 'Dash\\ReportsController');
});
/* ruote for Admin */
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/categories', 'Dash\\CategoriesController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/roles', 'Dash\\RolesController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/permissions', 'Dash\\PermissionsController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/users', 'Dash\\UsersController');
});
/* another routes */
Route::auth();
Route::get('/profile-edit/{id}', 'Dash\\UsersController#editUser');
My controller:
public function editUser($id)
{
$auth = Auth::user()->id;
$user = User::findOrFail($id);
if($auth == $user->id){
return view('dash.users.update_profile', compact('user'));
}
return redirect('errors/404');
}
public function storeUpdatedUser($id, Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'password' => 'required', 'surname' => 'required', ]);
$user = User::findOrFail($id);
$user->update($request->all());
$user->password = bcrypt($request->password);
$user->save();
Session::flash('flash_message', 'User updated!');
return redirect('/');
}
the view:
{!! Form::model($user, [
'method' => 'PATCH',
'url' => ['/profile-edit', $user->id],
'class' => 'form-horizontal'
]) !!}
........
WHere is the problem? And another problem is the field "password" show me a hased password, anyone can explaine me ?

You are sending a PATCH request to a get route:
Route::get('/profile-edit/{id}', 'Dash\\UsersController#editUser');
{!! Form::model($user, [
'method' => 'PATCH',
'url' => ['/profile-edit', $user->id],
'class' => 'form-horizontal'
]) !!}
Change the route from get to patch
Route::patch('/profile-edit/{id}', 'Dash\\UsersController#editUser');

Try to use Route::put('/profile-edit/{id}'...

solved:
Route::get('/profile-edit/{id}/edit', 'Dash\\UsersController#editUser');
Route::patch('/profile-edit/{id}', 'Dash\\UsersController#storeUpdatedUser');

Related

GET /account: Returns API Token on response

When the user created a new account I added it's API token and returned it to the user. But I'm having trouble wanting to return the API token to the user when they view their account information.
GET /account: Returns API Token in response.
This is my code file User.php:
public function index()
{
$users = User::where('id', auth()->user()->id)->get();
return response([
'data' => UserResource::collection($users),
'message' => 'Retrieve successfully'
], 200);
}
// POST
public function store(Request $request)
{
$data = $request->all();
$validator = Validator::make($data, [
'name' => 'required|max:255|string',
'email' => 'required|email|unique:users,email',
'password' => 'required|string',
]);
if ($validator->fails()) {
return response(['error' => $validator->errors(), 'Validation Error'], 400);
}
$users = User::create($data);
$token = $users->createToken('accessToken')->plainTextToken;
return response([
'data' => new UserResource($users),
'api_token' => $token,
'message' => 'Created successfully'
], 201);
}
This is my code file api.php (route):
Route::group(['prefix' => 'v1' ], function () {
// Account
Route::post('/account', [UserController::class, 'store']);
// Protected route
Route::group(['middleware' => ['auth:sanctum']], function () {
// Account
Route::get('/account', [UserController::class, 'index']);
});
});
Use $request->bearerToken() to get bearer token.
public function index()
{
$users = User::where('id', auth()->user()->id)->get();
return response([
'data' => UserResource::collection($users),
'api_token' => $request->bearerToken(),
'message' => 'Retrieve successfully'
], 200);
}

CreateFreshApiToken doesn't create the laravel_token cookie

As the title says CreateFreshApiToken doesnt create any cookies. So I cant use it to auth a logged in user for other requests related to the user.
I tried to set a cookie on the response and it works perfectly fine. So this has to do something with CreateFreshApiToken not working.
AuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
class AuthController extends Controller
{
public function signup(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string'
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$user->save();
return response()->json([
'message' => 'Successfully created user!'
], 201);
}
public function signin(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
$token->save();
return response()->json([
'message' => 'Successfully signed in!'
]);
}
public function signout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully signed out!'
]);
}
public function user(Request $request)
{
return response()->json($request->user());
}
public function test()
{
return response()->json([
'message' => 'test'
]);
}
public function test2(Request $request)
{
return response()->json([
'laravel_token' => $request->cookie('laravel_token')
]);
}
}
Kernel.php
protected $middlewareGroups = [
'web' => [
//...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
'api' => [
'throttle:60,1',
'bindings',
\Barryvdh\Cors\HandleCors::class,
],
];
api.php
Route::group([
'prefix' => 'auth'
], function () {
Route::post('signin', 'AuthController#signin');
Route::post('signup', 'AuthController#signup');
Route::get('test', 'AuthController#test');
Route::get('test2', 'AuthController#test2');
Route::group([
'middleware' => ['auth:api']
], function() {
Route::get('signout', 'AuthController#signout');
Route::get('user', 'AuthController#user');
});
});
And this is my angular code:
test() {
return this.http.get('http://homestead.test/api/auth/test', {withCredentials: true})
.subscribe(response => {
console.log(response);
});
}
test2() {
return this.http.get('http://homestead.test/api/auth/test2', {withCredentials: true})
.subscribe(response => {
console.log(response);
});
}
I've also setup cors with https://github.com/barryvdh/laravel-cors successfully with 'supportsCredentials' enabled. I am also sending a useless GET request to see if any laravel_token is set in the cookie but no success.
CreateFreshApiToken is part of the web middleware group, so in order for it to set cookies you need your login page to be a web route (instead of an api route).
I resolved this part of the problem by replicating CreateFreshApiToken::handler in my login controller:
$response = response()->json([], 200);
// ADD THIS LINE:
$response->cookie(\Laravel\Passport\Passport::cookie(),$request->session()->token();
return $response;

Laravel 5.5 Api Registration issue

I have been trying to get this api up and running and keep on experiencing this error when I test in Postman.
1. api.php
Route::group(['middleware' => ['api','cors']], function () {
Route::post('auth/register', 'Auth\RegisterController#create');
});
2. RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}}
Postman configuration set to Post, the body is set to raw and JSON(application/json) Below is the postman json code.
{
"name": "Walter White",
"email": "wwhite#someemaildomain.net",
"password": "testpassword"
}
Below is the error
Too few arguments to function App\Http\Controllers\Auth\RegisterController::create(), 0 passed and exactly 1 expected in file C:\xampp\examplestuff
In order to fix your registration you should change your route definition to:
Route::group(['middleware' => ['api','cors']], function () {
Route::post('auth/register', 'Auth\RegisterController#register');
});
I assume your RegisterController is using the trait RegistersUsers. This trait is providing the register method, which is using the RegisterController::create method to create the new user itself.
Pass Request to your create function like:
protected function create(Request $request){...
and access your data like this:
$request->name
you have to do validation also plz check below answer
protected function create(Request $request)
{
$data = $request->json()->all();
$validator = Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
if ($validator->fails()) {
foreach ($validator->messages()->getMessages() as $field_name => $message){
$messages[] = $message[0];
}
$messages = $messages;
$message = implode(',',$messages);
$response = $messages;
return $response;
}else{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}

Laravel 5.3 : Pages not loading properly

When the user log in or register, he is supposed to go the dashboard, but instead of it, it is being located to the /login page, which is not even there and hence error occours:
Sorry, the page you are looking for could not be found.
1/1
NotFoundHttpException in RouteCollection.php line 161:
Routes:
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::group(['middleware' => ['web']], function(){
Route::get('upload',function(){
return view('files.upload');
});
Route::get('/wallet',[
'uses' => 'WalletController#getwallet',
'as' => 'wallet'
]);
Route::post('/addmoney',[
'uses' => 'WalletController#addmoney',
'as' => 'addmoney'
]);
Route::post('/signup',[
'uses' => 'UserController#postSignUp',
'as' => 'signup'
]);
Route::post('/signin',[
'uses' => 'UserController#postSignIn',
'as' => 'signin'
]);
Route::get('/dashboard',[
'uses' => 'UserController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
Route::post('/handleUpload','FilesController#handleUpload');
Route::get('/pay', ['as' => 'pay', 'uses' => 'PaymentController#pay']);
# You will need one more.
Route::get('/payment/status', ['as' => 'payment_status', 'uses' => 'PaymentController#status']);
/**
* Using Named Routs to demonstrate all the possibilities.
*/
});
User controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use InvalidConfirmationCodeException;
use Flash;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class UserController extends Controller
{
public function getDashboard(){
return view('files.dashboard');
}
public function postSignUp(Request $request)
{
$this -> validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:20',
'password' => 'required|min:4'
]);
$email = $request['email'];
$name = $request['name'];
$password = bcrypt($request['password']);
$user = new User();
$user->email =$email;
$user->name = $name;
$user->password = $password;
$user->save();
return redirect()->route('dashboard');
//Auth::login($user);
}
public function postSignIn(Request $request)
{
$this -> validate($request,[
'email' => 'required',
'password' => 'required'
]);
if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) {
return redirect()->route('dashboard');
}
return redirect()->back();
}
}
WalletController
public function getwallet(){
return view('files.wallet');
}
public function addmoney(Request $request){
$this->validate($request,[
'amount'=>'required'
]);
$amount = $request['amount'];
$wallet = new Wallet();
$wallet->amount=$amount;
$wallet->save();
return redirect()->route('/addmoney');
}
Even when I try localhost:8000/dashboard , it loads as localhost:8000/login as shows same error.Also, same problem occurs when I try to load /addmoney page, when the user submit amount and redirect to the next addmoney page.
I see your dashboard view view is in file.controller but you use the auth middleware. Put your dashboard view in your dashboard view in the auth folder.
Default in Laravel: resources/views/auth/yourviewhere

session is not persisting.killed after redirect

Here is the code.If sign in it goes to /dashboard route. but after I go to other route user session is not persisting(by dd I found this).thanks in advance if you solve, I spent hours on this.
Route::group(['middleware' => 'web'],function(){
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::get('/dashboard' , [
'uses' => 'UserController#GetDashboard',
'as' => 'dashboard'
]);
Route::post('/signin' , [
'uses' => 'UserController#postSignin',
'as' => 'signin'
]);
});
in my login controller
public function postSignin(Request $request)
{
if(Auth::attempt(['email' => $request['email'],'password' => $request['password']])) {
return redirect()->route('dashboard');
}
return redirect()->back();
}
$request is an object, not an array. Try using $request->get('email').

Resources