get data value from jsonResponse Laravel 8 - laravel-8

I have two controller
the first one has a register method:
public function register(Request $request)
{
$generalTrait = new GeneralTrait;
$user = new User;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->type = $request->type;
$user->save();
return $generalTrait->returnData('user',$user);
}
and the second also has register method:
public function register(Request $request)
{
$generalTrait = new GeneralTrait;
$user = (new UserAuthController)->register($request);
$admin = Admin::create([
'admin_name' => $request->admin_name,
//'user_id' => $response->user->user_id,
'user_id' => $user_id
]);
//Admin created, return success response
return $generalTrait->returnSuccessMessage('Admin created successfully');
}
when I try to get data from (JsonResponse) $user I find this error:
ErrorException: Undefined property: Illuminate\Http\JsonResponse::$user
returnDate method in GeneralTrait return:
public function returnData($key, $value, $msg = ""){
return response()->json([
'status' => true,
'errNum' => "5000",
'msg' => $msg,
$key => $value
]);
}
I find same Error when I try to get the status from the $response
How can I fix it?

I fix it by replacing returnData with:
public function returnData($key, $value, $msg = ""){
return [
'status' => true,
'errNum' => "5000",
'msg' => $msg,
$key => $value
];}
so to get user_id from user I said:
'user_id' => ($response["user"])->user_id
I wish I knew what my mistake was, and how I could have fixed it some other way

Related

i was trying to check api on postman using phalcon and i got respon 400

I got this error when i try to check using postman... u can see the error below
i got this massage
"code":400,"response":"Failed","message":"Your username is not registered. Please register a new user now!","data":null
public function loginAction()
{
$this->view->disable();
$credentials = $this->request->getJsonRawBody();
$response = new Response();
$username = $credentials->username;
$password = $credentials->password;
// $user = User::findFirst("user_username = '$username'");
$user = User::findFirst([
'conditions' => 'username = :username:',
'bind' => [
'username' => $username
]
]);
if($user !== NULL) {
$checkPassword = $this->security->checkHash($password, $user->password);
if($checkPassword === true) {
$this->session->set('username', [
'id' => $username->id,
'username' => $user->username,
]);

Laravel 9 error route | The GET method is not supported

I am having a problem fetching a list of certain customers (authenticated users) via API. When I use this route in Postman I receive the following error.
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException:
The GET method is not supported for this route. Supported methods:
POST. in file
D:\api\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php
on line 118
api.php
Route::post('/register', [UserAuthController::class, 'register']);
Route::post('/login', [UserAuthController::class, 'login'])
->name('login');
Route::apiResource('/customer', CustomerController::class)
->middleware('auth:api');
Controller
class CustomerController extends Controller
{
public function index()
{
$customers = Customer::all();
return response([ 'customers' =>
CustomerResource::collection($customers),
'message' => 'Successful'], 200);
}
public function store(Request $request)
{
$data = $request->all();
$validator = Validator::make($data, [
'first_name'=>'required|max:120',
'email'=>'required|email|unique:users',
'password'=>'required|min:6'
]);
if($validator->fails()){
return response(['error' => $validator->errors(),
'Validation Error']);
}
$customer = Customer::create($data);
return response([ 'customer' => new CustomerResource($customer),
'message' => 'Success'], 200);
}
public function show(Customer $customer)
{
return response([ 'customer' => new CustomerResource($customer),
'message' => 'Success'], 200);
}
public function update(Request $request, Customer $customer)
{
$customer->update($request->all());
return response([ 'employee' => new CustomerResource($customer),
'message' => 'Success'], 200);
}
public function destroy(Customer $customer)
{
$customer->delete();
return response(['message' => 'Customer deleted']);
}
}
I solved this problem by adding Accept|json/application in headers of Postman.

Change Password in hashed function in laravel 5.6

I want to change my password which is been hashed while saving.
How can i change the password?
'password' => Hash::make($data->password).
My Controller
$request->validate([
'oldpass' => 'required',
'password' => 'required|alphaNum|min:6',
'password_confirmation' => 'required|same:newpass',
]);
$id = $request->id;
$users = Auth::user()->whereId($id)->get();
foreach ($users as $user) {
if ($oldpass == $user->password) {
$user->update([
'password' => Hash::make($request->newpass)
]);
return view('\balance');
} else {
return 'error';
}
}
You should use Hash::check($old_password, $hashed_password), something like this:
public function passwordChange(Request $request, User $user_name) {
// find the loggedin user
$user = User::find(Auth::user()->id);
// validate rules
$validator = Validator::make($request->all(), [
'old_password' => 'required|min:6',
'password' => 'required_with:password_confirmation|required|min:6',
'password_confirmation' => 'confirmed|required|min:6',
]);
// what to do if validator fails
if ($validator->fails()) {
return redirect($user->user_name . '/settings')->withErrors($validator)->withInput();
} else {
$old_password = $request->input('old_password');
$new_password = $request->input('password');
$hashed_password = Auth::user()->password;
// checking the old pass with new one
if (Hash::check($old_password, $hashed_password)) {
$user->update([
'password'=> Hash::make($new_password)
]);
return redirect($user->user_name . '/settings')->with('success', 'Your Password updated.');
} else {
return redirect($user->user_name . '/settings')->with('success', 'Your Old password is wrong!');
}
}
}
Please also notice 'password' => 'required_with:password_confirmation and 'password_confirmation' => 'required|same:newpass' on validator. Hope it helps.

error Call to a member function getChat() on null in package t telegram-bot-sdk

I'm using the data from telegrams received Webhook but I am faced with this error
Webhook tested properly set.
In your opinion, what is the problem?
This is my code:
Route :
Route::post('setwebhook','BotController#setWebhook');
Route::post('updates','BotController#updates');
BotController :
public function setWebhook()
{
$res = Telegram::setWebhook([
'url' => 'https://example.com/telegram-sdk/public/updates'
]);
return $res;
}
public function updates()
{
$update = Telegram::getWebhookUpdates();
$chat_id = $update->getMessage()->getChat()->getId();
$text = $update->getMessage()->getText();
$name = $update->getMessage()->getChat()->getFirstName();
if ($text == '/start') {
Telegram::sendMessage([
'chat_id' => $chat_id,
'text' => 'Hello World'
]);
}
}

call model in zend form using dependencies + zend framework 2

I am trying to fetch my category model in zend form for working out with select element with zend framework 2.
after lot of code searching I found I can either inject or pull dependencies.
Following code I did in my module.php
I want categoryTable.php(model) file in my CategoryForm.php
public function getServiceConfig()
{
return array(
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
'Category\Form\CategoryForm' => function ($sm) {
$service = $sm->get('Category\Model\CategoryTable');
$form = new Form;
$form->setService($service);
return $form;
}
),
);
}
then I put following code in my controller.
$form = $this->getServiceLocator()->get("Category\Form\CategoryForm");
Then I Put following code in my CategoryForm.php
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceLocator();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
And then I call it in same file like this way
public function __construct($name = null)
{
parent::__construct('category');
echo "<pre>";print_r($this->getCategoryTable());die;
.... other code
I found this error
Fatal error: Call to undefined method Category\Form\CategoryForm::getServiceLocator() in D:\wamp\www\zendapp\module\Category\src\Category\Form\CategoryForm.php on line 120
please help. and am I missing something?
I found the solution
Step :1
Here is my module.php code
public function getServiceConfig()
{
return array(
'invokables' => array(
'Category\Form\CategoryForm' => 'Category\Form\CategoryForm',
),
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
Step :2
Then in controller I made this change
// $form = new CategoryForm();
// Service locator now injected
$form = $this->getServiceLocator()->get('Category\Form\CategoryForm');
Step :3
Then In my categoryForm.php I made below changes
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
protected $serviceManager;
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceManager();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
protected function getCatList()
{
$groups = $this->getCategoryTable()->fetchAll();
return $groups;
}
public function getServiceManager()
{
if ( is_null($this->serviceManager) ) {
throw new Exception('The ServiceManager has not been set.');
}
return $this->serviceManager;
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
// Call the init function of the form once the service manager is set
$this->init();
return $this;
}
public function __construct($name = null) // constructor I finished immediately
{
parent::__construct('category');
}
I add INIT() function to fetch servicemanager
public function init()
{
$this->setAttribute('method', 'post');
$options = array();
foreach ($this->getCatList() as $cat) {
$options[$cat->id] = $cat->title;
}
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'parent_id',
'options' => array(
'label' => 'Parent Category',
'empty_option' => 'Please choose Parent Category',
'value_options' => $options,
),
));
}
Hope this will help who are new ZF2.