how to fix 500 internal server error in postman using laravel - php

service provider detail:
class ServiceProviderDetail extends Model {
protected $fillable = [
'working_status', 'booked', 'title', 'experience',
];
public function user()
{
return $this->belongsTo('App\User', 'user_id');
} }
add_booking:
class BookingController extends Controller {
public function addBooking(Request $request) {
//return $request;
$serviceman = ServiceProviderDetail::where('user_id', $request->service_provider_id)->first();
/********* Check if the serviceman is on duty ********/
if($serviceman->working_status !=1){
return response()->json([
'status'=> 0,
'message' => "Sorry pro has logged off duty",
'data' => []
], 200);
}
$serviceman->booked = '1';
if($request->input('subservice_id') == ''){
$service_id = $request->input('service_id');
} else {
$service_id = $request->input('subservice_id');
}
$booking = new Booking;
$booking->customer_id = $request->input('customer_id');
$booking->service_id = $service_id;
$booking->service_provider_id = $request->input('service_provider_id');
$booking->latitude = $request->input('latitude');
$booking->longitude = $request->input('longitude');
$booking->polyline = $request->input('polyline');
$booking->servicing_address = $request->input('servicing_address');
$booking->service_name = $request->input('service_name');
$booking->service_code = $request->input('service_code');
$booking->service_mobile = $request->input('service_mobile');
$booking->service_email = $request->input('service_email');
$booking->service_date = $request->input('service_date');
$booking->service_time = $request->input('service_time');
$booking->status = $request->input('status');
SendNotification::instance()->sendNotification('You have a new service request.',$booking->service_provider_id);
if($booking->save()) {
$serviceman->save();
return response()->json([
'status'=> 1,
'message' => 'Service booked successfully',
'data' => array(
$booking
),
], 200);
}
}
error_log:
emphasized textproduction.ERROR: Trying to get property 'working_status' of non-object {"exception":"[object] (ErrorException(code: 0): Trying to get property 'working_status' of non-object ...../BookingController.php:25)
[stacktrace]

$serviceman = ServiceProviderDetail::where('user_id', $request->service_provider_id)->first();
This is returning null. check if $serviceman is null before caling values

Related

ArgumentCountError Too few arguments to function App\Controllers\Blog::view()

Sorry for my bad english but i have a problem when i try to open localhost:8080/blog this message show up
Too few arguments to function App\Controllers\Blog::view(), 0 passed in C:\xampp\htdocs\baru\vendor\codeigniter4\framework\system\CodeIgniter.php on line 896 and exactly 1 expected
so this is the controller:
use CodeIgniter\Controller;
use App\Models\ModelsBlog;
class Blog extends BaseController
{
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
public function form(){
$data = [
'title' => 'Edit Form'
];
helper('form');
return view('view_form', $data);
}
public function view($id){
$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('view',$data);
}
public function simpan(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->SimpanBlog($data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Simpan');
}
public function form_edit($id){
$data = [
'title' => 'edit artikel'
];
$model = new ModelsBlog();
helper('form');
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('form_edit',$data);
}
public function edit(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$id = $this->request->getPost('id');
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$dt = $model->PilihBlog($id)->getRow();
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->edit_data($id,$data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Ubah');
}
public function hapus($id){
$model = new ModelsBlog();
$dt = $model->PilihBlog($id)->getRow();
$model->HapusBlog($id);
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Hapus');
}
}
ModelsBlog.php :
use CodeIgniter\Model;
class ModelsBlog extends Model
{
protected $table = 'artikel';
public function getArtikel()
{
return $this->findAll();
}
public function SimpanBlog($data)
{
$query = $this->db->table($this->table)->insert($data);
return $query;
}
public function PilihBlog($id)
{
$query = $this->getWhere(['id' => $id]);
return $query;
}
public function edit_data($id,$data)
{
$query = $this->db->table($this->table)->update($data, array('id' => $id));
return $query;
}
public function HapusBlog($id)
{
$query = $this->db->table($this->table)->delete(array('id' => $id));
return $query;
}
}
And this is the view.php:
<body style="width: 70%; margin: 0 auto; padding-top: 30px;">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2><?php echo $artikel->judul; ?></h2>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div class="row">
<?php
if (!empty($artikel->gambar)) {
echo '<img src="'.base_url("assets/blog/images/$artikel->gambar").'" width="30%">';
}
?>
<?php echo $artikel->isi; ?>
</div>
</div>
</div>
</body>
i cant find any solutions for this error, pls help thank you very much
Let's go over what you're telling the code to do.
First, you make a call to /blog. If you have auto-routing turned on this will put you forward to the controller named 'Blog'.
class Blog extends BaseController
And since you do not extend the URL with anything, the 'index' method will be called.
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
The index method sets $data to an array filled with 'title' => 'artikel'. And then fills $model with a new ModelsBlog.
class ModelsBlog extends Model
There is no __construct method defined in ModelsBlog so just the class is loaded and specific execution related to $model stops there, which is fine.
Then, the index() from Blog goes on and checks whether or not $this->validate([]) returns false. Since there's no else statement, if $this->validate([]) were to return true, code execution would stop there. So we'll assume $this->validate([]) returns false. So far so good, there's nothing weird going on with your code.
However, IF $this->validate([]) returns false, you tell the index() to return the function called view(). Normally CodeIgniter would serve you the view you set as the first parameter. But since you also have a Blog method named 'view', CodeIgniter will try to reroute te request to that method. So in other words, the actual request you're trying to make is:
Blog::view()
And since you've stated that view() receives 1 mandatory parameter, the requests triggers an error. You can solve the problem by either renaming the view() method of Blog to something like 'show()' or 'read()'. Anything else that does not conflict with the native CodeIgniter view() function would be good.
Honestly though, you are sending through two parameters in the index() function call so I'm slightly confused why the error generated states you provided 0, but I hope at least you gain some insight from my answer and you manage to fix the problem.
If anyone could provide more information regarding this, feel free to comment underneath and I'll add your information to the answer (if it gets accepted).

PayPal Laravel 8 integration using srmklive error

I want to integrate PayPal into my Laravel website but I'm getting this error:
Argument 1 passed to Symfony\Component\HttpFoundation\RedirectResponse::__construct() must be of the type string, null given, called in C:\xampp\htdocs\Delta\vendor\laravel\framework\src\Illuminate\Routing\Redirector.php on line 233
Controller File
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Srmklive\PayPal\Services\ExpressCheckout;
class PayPalController extends Controller {
public function __construct() {
$this->provider = new ExpressCheckout();
}
public function payment() {
$data = [];
$data['items'] = [
[
'name' => 'codechief.org',
'price' => 100,
'desc' => 'Description goes herem',
'qty' => 1
]
];
$data['invoice_id'] = 1;
$data['invoice_description'] = "Order #{$data['invoice_id']} Invoice";
$data['return_url'] = route('payment.success');
$data['cancel_url'] = route('payment.cancel');
$data['total'] = 100;
$provider = new ExpressCheckout;
$response = $provider->setExpressCheckout($data);
$response = $provider->setExpressCheckout($data, true);
return redirect()->away($response['paypal_link']);
}
Please give me a solution!
Actually, your problem is that $response['paypal_link'] isn't returning a link. Replace line:
return redirect()->away($response['paypal_link']);
With the code below:
if($response['paypal_link'] == null){
// custom redirection
return redirect()->back()->with(['error'=>'paypal link no set'])
}
return redirect()->away($response['paypal_link']);
For more info visit laravel-paypal

Laravel 5.6, where to keep additional classes (additional functional)?

I need to make request on some CRM api in my controller. For making this I have pretty big method. It's look like ugly. I know that there are some "Services" and to put additional code into Service is a good way. But I don't know what is this. Is it a custom classes into app folder? Or maybe it's Service-providers? I have read service-providers documentation and I'm not sure that service-providers is suitable for this. Here is my code:
<?php
namespace App\Http\Controllers;
use App\User;
use App\UserInfo;
use Validator;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$users = User::with('info')
->paginate(20);
$users->withPath(DIRECTORY_SEPARATOR . $request->path() .DIRECTORY_SEPARATOR);
return response()->json($users)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = $request->json()->all();
$rules = [
'name' => 'required',
'phone' => 'required|unique:users'
];
$validator = Validator::make($data, $rules);
if ($validator->fails()) return response()->json(['errors'=>$validator->errors()]);
$user = new User();
$user->name = request('name');
$user->phone = request('phone');
$user_info_obj = $this->storeUserInfo();
if($user_info_obj === null){
return response('Impassible to define user geo data', 400);
}
$user->info_id = $user_info_obj->id;
$user->save();
$this->makeAMOLead($user->name,
$user->phone,
$user_info_obj->user_agent,
$user_info_obj->city,
$user_info_obj->country);
return response()->json(['success' => 'User created successfully']);
}
public function storeUserInfo()
{
$ip = request()->ip();
$reader = new \GeoIp2\Database\Reader('../resources/geo-lite2-city_20180807/GeoLite2-City.mmdb');
try {
$record = $reader->city($ip);
}
catch (\Throwable $e){
// Code bellow is for testing on localhost, Because of maybe exception instead of geo obj on localhost.
$info = new UserInfo();
$info->ip = '127.0.0.1';
$info->city = 'Some city';
$info->country = 'Some country';
$info->country_code = 'Some code';
$info->continent = 'Some continent';
$info->continent_code = 'no';
$info->user_agent = 'User agent';
$info->save();
return $info;
//return null;
}
$city = $record->city->names['ru'];
$continent = $record->continent->names['ru'];
$continent_code = $record->continent->code;
$country = $record->country->names['ru'];
$country_code = $record->country->isoCode;
$user_agent = \request()->userAgent();
$info = new UserInfo();
$info->ip = $ip;
$info->city = $city;
$info->country = $country;
$info->country_code = $country_code;
$info->continent = $continent;
$info->continent_code = $continent_code;
$info->user_agent = $user_agent;
$info->save();
return $info;
}
private function makeAMOLead($name, $phone, $userAgent, $city, $country)
{
$domain = env('AMO_DOMAIN');
$login = env('AMO_LOGIN');
$hash = env('AMO_HASH');
try {
$credentials = new \ddlzz\AmoAPI\CredentialsManager($domain, $login, $hash);
$settings = new \ddlzz\AmoAPI\SettingsStorage();
$settings->setCookiePath(env('AMO_COOKIE_FILE_PATH'));
$request = \ddlzz\AmoAPI\ClientFactory::create($credentials, $settings);
$lead = new \ddlzz\AmoAPI\Model\Amo\Lead();
$lead['name'] = $name;
if(env('AMO_PIPELINE_ID', null)){
$lead['pipeline_id'] = intval(env('AMO_PIPELINE_ID'));
}
$lead['name'] = 'New pickup user ' . $name;
$lead['custom_fields'] = [
[
'id' => env('AMO_NAME_FIELD_ID'),
'values' => [
['value' => $name],
]
],
[
'id' => env('AMO_USER_AGENT_FIELD_ID'),
'values' => [
['value' => $userAgent]
]
],
[
'id' => env('AMO_CITY_FIELD_ID'),
'values' => [
['value' => $city]
]
],
[
'id' => env('AMO_COUNTRY_FIELD_ID'),
'values' => [
['value' => $country]
]
],
];
$lead['created_at'] = time();
$result = $request->add($lead);
$pipelineId = json_decode($result)->_embedded->items{0}->id;
// create contact
$contact = new \ddlzz\AmoAPI\Model\Amo\Contact();
$contact['name'] = $name;
$contact['created_at'] = time();
$contact['leads_id'] = "$pipelineId";
// dd($request->accountInfo(), true); // Call this, if you need to know ids of default fields (like phone, or position)
$contact['custom_fields'] = [
[
'id' => env('AMO_CONTACT_PHONE_ID'),
'values' => [
[
'value' => $phone,
'enum' => 'MOB',
],
]
],
];
$result = $request->add($contact);
} catch (Exception $e) {
echo response()->json(['error' => $e->getFile() . ': ' . $e->getMessage()]);
}
}
}
Look on the makeAMOLead. This is big method in my controller and this is not ok for controller conception.
Please use repository pattern to split all the communication between the application and your data source. and call the repository functions inside your controller. It is good practice. Here is an article you can understand about that
Example:
Your functions can be separate from controller to repository.
storeUserInfo
makeAMOLeadin
Move your functions an repository and call them into your controller.

getting error &#039 in yii2 advance

Exception 'yii\base\InvalidArgumentException' with message 'Response content must not be an array.'
in C:\xampp1\htdocs\advanced\vendor\yiisoft\yii2\web\Response.php:1054
Stack trace:
0 C:\xampp1\htdocs\advanced\vendor\yiisoft\yii2\web\Response.php(337): yii\web\Response->prepare()
1 C:\xampp1\htdocs\advanced\vendor\yiisoft\yii2\base\Application.php(392): yii\web\Response->send()
2 C:\xampp1\htdocs\advanced\frontend\web\index.php(17): yii\base\Application->run()
3 {main}
SiteController.php
public function actionGetuser()
{
$model = new UsersData();
if(Yii::$app->request->isAjax){
$id = Yii::$app->request->post();
return $model->get($id);
}
}
model:-
function get($id)
{
$model = Yii::$app->db->createCommand("SELECT * FROM user where id=$id");
return $user = $model->queryOne();
}
I got the solution :-
model:-
function get($id)
{
$userid = json_decode($id);
$uid = $userid->id;
$model = Yii::$app->db->createCommand("SELECT * FROM user where id = $uid");
$user = $model->queryOne();
//return $user;
return json_encode($user);
}
controller:-
public function actionGetuser()
{
$model = new UsersData();
//return "Dfasdafsd";
if(Yii::$app->request->isAjax){
$data = Yii::$app->request->post();
$id = json_encode($data);
return $model->get($id);
}
}
You need to change format of your response :
You can modify its configuration by adding an array to your application config under components as it is shown in the following example:
'response' => [
'format' => yii\web\Response::FORMAT_JSON,
'charset' => 'UTF-8',
// ...
]
Check This Link For More info
OR
function get($id)
$result = user::find()->where(['id' => $id])->all();
return Json::encode($result);
}

Unresolvable dependency resolving within Laravel

I get the error when calling a custom function I created:
namespace App\Jobs\Device;
class UpdateUserReference {
public $installationReference;
public $userReference;
// assign payload data and installation id received to command
function __construct($bodyContent) {
$this->installationReference = $bodyContent["installationReference"];
$this->userReference = $bodyContent["userReference"];
}
}
Unresolvable dependency resolving [Parameter #0 [ $bodyContent ]] in class App\Jobs\Device\UpdateUserReference
Strange enough I never had the error before and I create my function exactly the same as for all other cases. What is wrong with the bodyContent variable I provide?
The function is called within:
public function update(Request $request) {
// Get payload from request
$bodyContent = json_decode($request->getContent(), true);
$action = $bodyContent["action"];
$installationReference = $bodyContent["installationReference"];
switch($action) {
case 'userReference':
$updateUserReference = new UpdateUserReference($bodyContent);
$result = $this->commandBus->execute($updateUserReference);
break;
}
if (!empty($result)) {
$response = [
'error' => [
'code' => 400,
'message' => "Update Error"
]
];
return $this->setStatusCode(400)->respond($response);
}
$response = [
'data' => [
'installationReference' => $installationReference
]
];
return $this->setStatusCode(201)->respond($response);
}

Categories