Laravel - POSTMAN Login Internal Server Error - laravel

I am using Laravel-5.8 as backend for an application. I have written all the Api for the endpoints.
Laravel: ApiController
protected function guard()
{
return Auth::guard();
}
public function returnResponse($success, $data, $errorCode = 0, $message = false) {
$response = array();
$response['success'] = $success;
$response['message'] = isset($message) ? $message : '';
if ($errorCode) {
$response['errorCode'] = isset($errorCode) ? $errorCode : 0;
}
$response['data'] = $data;
return response()->json($response, 200);
}
public function login() {
$authenticated = false;
$remember = request('remember') ? true : false;
if (Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password')], $remember)) {
$authenticated = true;
}
if ($authenticated == true) {
$user = Auth::guard('web')->user();
$date = date('Y-m-d');
$success['userId'] = $user->id;
$success['avatar'] = url('/storage/user') . '/' . $user->avatar;
// $success['points'] = $user->userPoints->sum('points');
$success['email'] = $user->email;
$success['token'] = $user->createToken('MyApp')->accessToken;
return $this->returnResponse(true, $success);
} else {
$success = array();
return $this->returnResponse(false, $success, 1, 'Invalid User Credential');
}
}
api.php
Route::group([
], function () {
Route::post('login', 'ApiController#login');
Route::post('register', 'ApiController#register');
Route::post('forgetPassword', 'ApiController#forgetPassword');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
});
When I test the login Post Request on the POSTMAN, I got the error shown below:
What could have caused the error?

i think you have declare index() multiple times in your controller so please check and if there is multiple times declaration of index() then just remove anyone.

Related

Multistep form using ajax in Laravel 8

I created a multistep form but I didn't use Ajax in it because I have no idea about Ajax. I have had to code a lot in my controller and routes for the way I created it which is probably not optimized. I'm new to Laravel so I can't find any solution.
How can I do this with ajax?
Controller
public function InitialCreateReport(Request $request){
$request->session()->forget('report');
$data['fiscalyear'] = FiscalYear::all();
$data['month'] = Months::all();
$data['report_type'] = ReportType::all();
$data['report'] = $request->session()->get('report');
return view('adc.reports.create-report', $data);
}
public function PostInitialCreateReport(Request $request){
$validatedData = $request->validate([
'fiscalyear' => 'required',
'month' => 'required',
'report_type' => 'required',
]);
if (empty($request->session()->get('report'))) {
$report = new Report();
$report->fill($validatedData);
$request->session()->put('report', $report);
} else {
$report = $request->session()->get('report');
$report->fill($validatedData);
$report->session()->put('report', $report);
}
return redirect()->route('adc.create.rent.certificate');
}
public function CreateRentCertificateReport(Request $request)
{
$data['report'] = $request->session()->get('report');
$data['reports'] = Report::distric()->status(1)->get();
return view('adc.reports.start-create-report', $data);
}
public function PostCreateRentCertificateReport(Request $request)
{
$report = $request->session()->get('report');
$request->session()->put('report', $report);
return redirect()->route('adc.preview.rent.certificate.report');
}
public function PreviewRentCertificateReport(Request $request){
$report = $request->session()->get('report');
return view('adc.reports.preview-rent-certificate-report', compact('report', $report));
}
public function PostPreviewRentCertificateReport(Request $request){
$report = $request->session()->get('report');
return redirect()->route('adc.save.rent.certificate.report');
}
public function SaveRentCertificateReport(Request $request){
$report = $request->session()->get('report');
return view('adc.reports.save-rent-certificate-report', compact('report', $report));
}
public function PostSaveRentCertificateReport(Request $request)
{
$report = $request->session()->get('report');
$reports = new Report;
$reports->column_one = $report->sum('column_one');
$reports->column_two = $report->sum('column_two');
$reports->fiscal_year = $report->fiscalyear;
$reports->month = $report->month;
$reports->report_type = $report->report_type;
$reports->save();
$notification = array(
'message' => 'Report Created Successfully',
'alert-type' => 'success'
);
return redirect()->route('adc.pending.report')->with($notification);
}
Route
Route::get('/initial/create/report', [AdcController::class,'InitialCreateReport'])->name('inital.create.report');
Route::post('/initial/create/report', [AdcController::class,'PostInitialCreateReport'])->name('inital.create.report.post');
Route::get('/create/rent/certificate/report', [AdcController::class, 'CreateRentCertificateReport'])->name('create.rent.certificate');
Route::post('/create/rent/certificate/report', [AdcController::class, 'PostCreateRentCertificateReport'])->name('create.rent.certificate.report.post');
Route::get('/preview/rent/certificate/report', [AdcController::class, 'PreviewRentCertificateReport'])->name('preview.rent.certificate.report');
Route::post('/preview/rent/certificate/report', [AdcController::class, 'PostPreviewRentCertificateReport'])->name('preview.rent.certificate.report.post');
Route::get('/save/rent/certificate/report', [AdcController::class, 'SaveRentCertificateReport'])->name('save.rent.certificate.report');
Route::post('/save/rent/certificate/report', [AdcController::class, 'PostSaveRentCertificateReport'])->name('save.rent.certificate.report.post');

Object of class Illuminate\Routing\Redirector could not be converted to string. srmklive/laravel-paypal

I am currently working on a paypal checkout using paypal and https://github.com/srmklive/laravel-paypal. I'm using the express checkout which I modified it a little bit to fit the requirements of the my project. During testing it is working in a couple of tries, paypal show and payment executes properly but when I tried to run the exact same code. I get this error I don't know what it means.
I tried to check my routes if it all of the errors happens to my routes but all of it are working properly. I also tried dump and die like dd("check") just to check if its really going to my controller and it does. I did this in the method "payCommission" (this where the I think the error happens)
This is my route for the controller
api.php
Route::get('service/commissionfee/payment' , 'api\service\ExpressPaymentController#payCommission');
Route::get('paypal/ec-checkout-success', 'api\service\ExpressPaymentController#payCommissionSuccess');
ExpressPaymentController.php
<?php
namespace App\Http\Controllers\api\service;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Srmklive\PayPal\Services\ExpressCheckout;
class ExpressPaymentController extends Controller
{
protected $provider;
public function __construct()
{
try {
$this->provider = new ExpressCheckout();
}
catch(\Exception $e){
dd($e);
}
}
public function payCommission(Request $request)
{
$recurring = false;
$cart = $this->getCheckoutData($recurring);
try {
$response = $this->provider->setExpressCheckout($cart, $recurring);
return redirect($response['paypal_link']);
} catch (\Exception $e) {
dd($e);
return response()->json(['code' => 'danger', 'message' => "Error processing PayPal payment"]);
}
}
public function payCommissionSuccess(Request $request)
{
$recurring = false;
$token = $request->get('token');
$PayerID = $request->get('PayerID');
$cart = $this->getCheckoutData($recurring);
// ? Verify Express Checkout Token
$response = $this->provider->getExpressCheckoutDetails($token);
if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
if ($recurring === true) {
$response = $this->provider->createMonthlySubscription($response['TOKEN'], 9.99, $cart['subscription_desc']);
if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
$status = 'Processed';
} else {
$status = 'Invalid';
}
} else {
// ? Perform transaction on PayPal
$payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
$status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
}
return response()->json(['success' => "payment complete"]);
}
}
private function getCheckoutData($recurring = false)
{
$data = [];
$order_id = 1;
$data['items'] = [
[
'name' => 'Product 1',
'price' => 9.99,
'qty' => 1,
],
];
$data['return_url'] = url('api/paypal/ec-checkout-success');
// !
$data['invoice_id'] = config('paypal.invoice_prefix').'_'.$order_id;
$data['invoice_description'] = "Commission Fee payment";
$data['cancel_url'] = url('/');
$total = 0;
foreach ($data['items'] as $item) {
$total += $item['price'] * $item['qty'];
}
$data['total'] = $total;
return $data;
}
}
Error I am getting
Object of class Illuminate\Routing\Redirector could not be converted to string
Thank you in advance
you may just go to the config/paypal.php and edit
'invoice_prefix' => env('PAYPAL_INVOICE_PREFIX', 'Life_saver_'),
you may use _ underline in this like Life_saver_, dont forget use underline at the end too.

Multiuser login codeigniter(how to use password_verify method?)

Please help guys, I have encrypted successfully my password with password_hash but is there any solution how to check login and password using PHP password_verify for multiuser login?
here's my controller:
public function index()
{
$this->form_validation->set_rules('email','Email address','required');
$this->form_validation->set_rules('password','Password','required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('view_login');
} else {
$this->load->model('Model_members');
$valid_user = $this->Model_members->check_credential();
if($valid_user == FALSE)
{
$this->session->set_flashdata('error','');
redirect("login");
} else {
$this->session->set_userdata('email', $valid_user->email);
if($this->session->userdata('groups') == '1')
{
redirect('home');
}
elseif($this->session->userdata('groups') == '2')
{
redirect('homepage');
}
elseif($this->session->userdata('groups') == '0')
{
redirect('test1');
}
}
}
}
This is my model:
public function check_credential()
{
$email = set_value('email');
$password = set_value('password');
$hasil3 = $this->db->where('email', $email)
->where('password', $password)
->limit(1)
->get('users');
if($hasil3->num_rows() > 0)
{
return $hasil3->row();
} else {
return array();
}
}
Very appreciate for the help !!
Please find below mentioned solution, It will help you.
In Controller
$userData['email'] = $this->input->post('email');
$userData['password'] = $this->input->post('password');
$valid_user = $this->Model_members->check_credential($userData);
In Model your function will look like below.
public function check_credential($param) {
$hasil3 = $this->db->where('email', $param['email'])
->where('password', password_hash($param['password'], PASSWORD_DEFAULT, ['cost' => 10]))
->limit(1)
->get('users');
if ($hasil3->num_rows() > 0) {
return $hasil3->row();
} else {
return array();
}
}
Let me know if it not work.
Controller
//create array to pass data to model
$data = [
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
];
//check model to see if user exists and if correct password
$user = $this->name_of_model->check_credential($data);
if(isset($user['error])){
//return error message in some form
}
Model:
You want to break you process in two, in order to make error reporting better. First check if user exists, then check if password is correct
public function check_credential($data) {
//see if user exists first
$user = $this->db->where('email', $data['email'])
->get('users')->row_array();
if($user){
$success = (password_verify($data['password'],$user['password']));
return ($success) ? $user : ['error'=>'Incorrect Password']
}
else{
return ['error'=>'User doesn't exist'];
}
}

Trying to get property of non-object when using Auth in service provider

I get an error 'Trying to get property of non-object' in my service provider when I used Auth :
public function boot()
{
$roles = DB::table('folders')->orderBy('folder_id', 'desc')->where('level', 0)->get();
if(Auth::user()->level == 1){
$roles1 = DB::table('folders')->orderBy('folder_id', 'asc')->where('level', 1)->get();
}else{
$user = DB::table('folder_permissions')->where('user_id', Auth::user()->id)->get();
foreach($user as $u){
$roles1 = DB::table('folders')->orderBy('folder_id', 'asc')->where('level', 1)->get();
}
}
$treeFolder = DB::table('folders')->where('level', 0)->get();
if(!empty($treeFolder)){
foreach($treeFolder as $folders){
$arrayCategories[$folders->folder_id] = array("parent_id" => $folders->parent, "name" => array("fname" => $folders->folder_name, "id" => $folders->folder_id));
}
}else{
$arrayCategories = FALSE;
}
view()->share(['folder' => $roles, 'prime_folders' => $roles1, 'treeView' => $arrayCategories]);
}
I already called 'use Illuminate\Support\Facades\Auth;', but nothing happen.
Can somebody help me ?
it seems that, Auth is loading before everything get ready. you just follow this, it works
view()->composer('*', function ($view)
{
$roles = DB::table('folders')->orderBy('folder_id', 'desc')->where('level', 0)->get();
if(Auth::user()->level == 1){
$roles1 = DB::table('folders')->orderBy('folder_id', 'asc')->where('level', 1)->get();
}else{
$user = DB::table('folder_permissions')->where('user_id', Auth::user()->id)->get();
foreach($user as $u){
$roles1 = DB::table('folders')->orderBy('folder_id', 'asc')->where('level', 1)->get();
}
}
$treeFolder = DB::table('folders')->where('level', 0)->get();
if(!empty($treeFolder)){
foreach($treeFolder as $folders){
$arrayCategories[$folders->folder_id] = array("parent_id" => $folders->parent, "name" => array("fname" => $folders->folder_name, "id" => $folders->folder_id));
}
}else{
$arrayCategories = FALSE;
}
//if this line doesn't work then.... see below line after this coming up line
$view->share(['folder' => $roles, 'prime_folders' => $roles1, 'treeView' => $arrayCategories]);
$view->with('folder', $roles)->with('prime_folders',$roles1)->with('treeView',$arrayCategories);
});

ErrorException Undefined variable: code (View: C:\wamp\www\secureserver\app\views\emails\adminverify.blade.php)

I have been toiling around to no avail of Solutions Please help. It seems my View cannot read the $code and $user variable respectively from my Controller
Here is the part of my controller that the $code and $user Variables are been instantiated respectively:
UserController.php
public function varifyMail($code){
if(User::where('varification_code','=',$code)->update(['varification_status'=>1])){
return Redirect::route('login')
->with('success', 'Account varified.');
}else{
return Redirect::route('login')
->with('error', 'Varification Failed.Try again');
}
);
$validation = Validator::make(Input::all(),$rules);
if($validation->fails()){
return Redirect::route('login')
->with('error', 'Invalid Email Address. Try again.');
}else{
$code = str_random(25);
$userUpdate = ['recovery_code' => $code];
User::where('email','=',Input::get('email'))->update($userUpdate);
$data = ['code'=>$code];
//send mail
Mail::send('emails.recover',$data,function($message){
$message->to(Input::get('email'))->subject('Recover Your Account.');
});
return Redirect::route('login')
->with('success', 'Request Send successfully.Please Recover Your Account.');
//return User::where('email','=',Input::get('email'))->get();
}
Auth::login($user);
return View::make('users.edit')
->with('title','Update Cridentials')
->with('user',User::where('id','=',$user->id)->first());
}else{
return Redirect::route('login')
->with('error', 'Recovery Failed.Try again');
}
And this is my view:
Adminverify.blade.php
<div class="header-content"><webversion>Web Version</webversion><span class="hide"> | <preferences lang="en">Update preferences</preferences> | </span>
But whenever I try using it it get this error:
ErrorException
Undefined variable: code (View: C:\wamp\www\secureserver\app\views\emails\adminverify.blade.php)
Any Help will be highly Appreciated Thanks!
Thanks for your prompt response but it happens to be that it did not work but here is my entire Controller with the Varify changed to Verify as cadmium suggested so we can be sure what exactly could be the challenge.
class UserController extends BaseController {
private function verify($email){
$verify = User::where('email','=',$email)->first();
if(! is_null($verify)){
if($verify->role_id==2){
return $verify->distributor_approve & $verify->varification_status;
}else{
return $verify->varification_status;
}
}else{
return 0;
}
}
/**
* login page
* #return void
*/
public function login()
{
return View::make('users.login')
->with('title', 'Log in');
}
/**
* process to login a user
* #return void
*/
public function doLogin()
{
$rules = array
(
'email' => 'required|email',
'password' => 'required'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
return Redirect::route('login')
->withInput()
->withErrors($validation);
else
{
$credentials = array
(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if($this->verify(Input::get('email')) && Auth::attempt($credentials))
{
Session::put('role', Auth::user()->role_id);
//return User::where('id','=',Auth::user()->id)->first();
if(User::where('id','=',Auth::user()->id)->first()->first_login == 0){
return Redirect::route('info.create',[Auth::user()->id]);
}
return Redirect::intended('/');
}
else
return Redirect::route('login')
->withInput()
->with('error', 'Error in Email Address or Password.');
}
}
/**
* logout a user
* #return void
*/
function logout()
{
Auth::logout();
Session::forget('role');
return Redirect::route('login')
->with('success', 'You have been logged out.');
}
public function show(){
$pages= Page::orderby('title')->get();
if(Auth::check()){
if(Auth::user()->role_id==1){
return View::make('public.pages.admin')
->with('title', "Home");
}
}
return View::make('public.pages.show')
->with('title', "Home")
->with('pages',$pages);
}
public function register()
{
return View::make('users.register')
->with('title', 'Register');
}
public function doRegister()
{
//return Input::all();
$rules = array
(
'username' => 'required|min:3|max:15',
'email' => 'required|email|unique:users',
'password' =>'Required|Confirmed',
'password_confirmation' =>'Required',
'role' => 'Required',
'agree' => 'Required',
'recaptcha_response_field' => 'required|recaptcha'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
return Redirect::route('register')
->withInput()
->withErrors($validation);
else
{
if(Input::get('role')==3){
$user = new User;
$user->user_name = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->role_id = Input::get('role');
$code = str_random(25);
$user->varification_code = $code;
$data = ['username'=>Input::get('username'),'code'=>$code];
Mail::send('emails.validate',$data,function($message){
$message->to(Input::get('email'))->subject('Please Verify Your Email.');
});
if($user->save())
return Redirect::route('home')
->with('success', "Verify Your Account.");
else
return Redirect::back()->withInput()->withErrors($validation)->with('error', 'Some error occured. Try again.');
}else{
$user = new User;
$user->user_name = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->role_id = Input::get('role');
$user->distributor_status = 1;
$code = str_random(25);
$user->varification_code = $code;
$data = ['username'=>Input::get('username'),'code'=>$code];
Mail::send('emails.validate',$data,function($message){
$message->to(Input::get('email'))->subject('Please Verify Your Email.');
});
if($user->save())
return Redirect::route('home')
->with('success', "Request Send successfully.Please Verify Your Email.");
else
return Redirect::back()->withInput()->withErrors($validation)->with('error', 'Some error occured. Try again.');
}
}
}
public function edit(){
return View::make('users.edit')
->with('title','Update Cridentials')
->with('user',User::where('id','=',Auth::user()->id)->first());
}
public function update(){
$rules = array
(
'username' => 'required|min:3|max:15',
'password' =>'Required|Confirmed',
'password_confirmation' =>'Required'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
return Redirect::back()
->withInput()
->withErrors($validation);
else
{
$userUpdate = ['user_name' => Input::get('username'),
'password'=>Hash::make(Input::get('password'))
];
if(User::find(Auth::user()->id)->update($userUpdate)){
Auth::logout();
Session::forget('role');
return Redirect::route('login')
->with('success', 'Your Cridentials Have Been Changed.');
}
else
return Redirect::back()->withInput()->withErrors($validation)->with('error', 'Some error occured. Try again.');
}
}
public function verifyMail($code){
if(User::where('varification_code','=',$code)->update(['varification_status'=>1])){
return Redirect::route('login')
->with('success', 'Account varified.');
}else{
return Redirect::route('login')
->with('error', 'Varification Failed.Try again');
}
}
public function passwordRecover(){
$rules = array
(
'email' => 'required|email'
);
$validation = Validator::make(Input::all(),$rules);
if($validation->fails()){
return Redirect::route('login')
->with('error', 'Invalid Email Address. Try again.');
}else{
$code = str_random(25);
$userUpdate = ['recovery_code' => $code];
User::where('email','=',Input::get('email'))->update($userUpdate);
$data = ['code'=>$code];
//send mail
Mail::send('emails.recover',$data,function($message){
$message->to(Input::get('email'))->subject('Recover Your Account.');
});
return Redirect::route('login')
->with('success', 'Request Send successfully.Please Recover Your Account.');
//return User::where('email','=',Input::get('email'))->get();
}
}
public function mailRecover($code){
$user = User::where('recovery_code','=',$code)->first();
if(! is_null($user)){
Auth::login($user);
return View::make('users.edit')
->with('title','Update Cridentials')
->with('user',User::where('id','=',$user->id)->first());
}else{
return Redirect::route('login')
->with('error', 'Recovery Failed.Try again');
}
}
/**
* Show a page
* #param string $pageUrl
* #return void
*/
public function pages($pageUrl = 'home')
{
try
{
$page = Page::where('url', '=', $pageUrl)->firstOrFail();
/*
if($page->id == 1) $layout = 'layouts.home';
else $layout = 'layouts.default';
*/
$layout = 'layouts.default';
return View::make('public.pages.publicShow')
->with('title', "$page->title")
->with('page', $page)
->with('layout', $layout);
}
catch(ModelNotFoundException $e)
{
return "Page not found.";
}
}
Somewhere in your code you need to have View::make("adminverify"). I don't see it in the code you've posted, but it's there somewhere. You need to pass the $code value to this view, like so:
View::make("adminverify")->with("code", "some code value");
Once you do that, the $code variable will be available in the template.

Resources