Unable to implement mongor bundle in laravel - laravel

I am trying to implement mongor bundle for laravel version 3.2.14
I have followed all the steps as mentioned in the documentation on mongor homepage
There is no documentation regarding its usage in the homepage but by chance i got the following link : bundle full example
In-spite of following this i am unable to understand why my code is not working.
Strangely i am not getting any errors.
My code is as follows
database.php
'mongor' => array(
'hostname' => '127.0.0.1',
'connect' => true,
'timeout' => '',
'replicaSet' => '',
'db' => 'census',
'username' => 'root',
'password' => '',
),
user.php(Model)
class User extends Mongor\Model{
public static $timestamps = true;
public function __construct($connection = NULL)
{
parent::__construct($connection);
static::$collection = 'user';
}
}
user.php(Controller)
public function get_index()
{
//return View::make('user.index');
$users = User::first();
dd($users);
}
I am getting following data when i execute this url:
object(User)#28 (14) {
["connection"]=>
object(Mongor\MongoDB)#29 (4) {
["_name":protected]=>
NULL
["_connected":protected]=>
bool(true)
["_connection":protected]=>
object(Mongo)#30 (4) {
["connected"]=>
bool(true)
["status"]=>
NULL
["server":protected]=>
string(19) "mongodb://localhost"
["persistent":protected]=>
NULL
}
["_db":protected]=>
object(MongoDB)#31 (2) {
["w"]=>
int(1)
["wtimeout"]=>
int(10000)
}
}
["exists"]=>
bool(false)
["attributes"]=>
NULL
["dirty"]=>
array(0) {
}
["ignore"]=>
array(0) {
}
["includes"]=>
array(0) {
}
["relating"]=>
NULL
["relating_key"]=>
NULL
["relating_table"]=>
NULL
["_limit"]=>
NULL
["_skip"]=>
NULL
["_where"]=>
array(0) {
}
["_sort"]=>
array(0) {
}
["_count":protected]=>
NULL
}
Whereas when i execute the command db.user.find() in the mongo shell i get all the relevant results.

Related

Axios returns error status code 500 when there is data present

I am using Laravel 8, VueJS and Axios for my application then every time I try to fetch all records from my database it returns an error with status code 500. Even though when fetching the data using Postman/Insomnia it returns the data without an error.
I tried to empty the table where it fetches the data the error disappears and it returns empty data with status code 200.
Store Module:
import axios from 'axios'
export default {
namespaced: true,
state: {
courses: [],
teacher: '',
},
getters: {
allCourses(state) {
return state.courses
},
},
actions: {
async fetchAllCourses({ commit }) {
const response = await axios.get('teacher/course-management/list')
console.log(response.data.data)
commit('SET_COURSES', response.data.data)
}
},
mutations: {
SET_COURSES(state, courses) {
state.courses = courses
}
}
Controller:
public function fetchAllCourses() {
try {
$courses = Course::all()->sortBy('id');
$data = $courses->transform(function ($course) {
// ! Get teacher id
$teacherId = $this->user->teacher->id;
// ! Get teacher name by id
$teacherName = $this->getTeacherName($teacherId);
return [
'id' => $course->id,
'teacher_id' => $course->teacher_id,
'teacher' => $teacherName,
'section' => $course->section,
'code' => $course->code,
'status' => $course->status,
'image' => $course->image,
];
});
return $this->success('Request success', $data);
} catch (\Exception $e) {
return $this->error($e->getMessage(), $e->getCode());
}
}
Problem solved.
public function fetchAllCourses() {
try {
$courses = Course::all()->sortBy('id');
$data = $courses->transform(function ($course) {
return [
'id' => $course->id,
'teacher_id' => $course->teacher_id,
'teacher' => $this->getTeacherName($course->teacher_id),
'section' => $course->section,
'code' => $course->code,
'status' => $course->status,
'image' => $course->image,
];
});
return $this->success('Request success', $data);
} catch (\Exception $e) {
return $this->error($e->getMessage(), $e->getCode());
}
}

Laravel Http Client 419 unknown status

For testing reasons, I want to make the following Post Request with the Laravel HTTP Client:
$test = Http::post(route('users.leads.store', ['user' => $user->id]), [
"company_name" => "TESTCOMPANY",
"zip" => "49685",
"city" => "BÜHREN",
"street" => "MÜHLENKAMP 3",
"contact_name" => "FABIANLUKASSEN",
"phone1" => "017691443785",
"email" => "FABIANLUKASSEN#TESTEN.DE",
"website" => "www.fabianlukassen.de",
"category" => "Hotel",
"closed_until" => now(),
"appointment_end" => now()->addDays(1),
"appointment_comment" => "HALLO ICH BIN FABIAN",
"additional_contacts" => "",
"phone2" => "",
"sub_category" => "",
"expert_status" => 0
]);
I know that the route is working just fine. However, with debugging in phpStorm, I can see that the $test variable contains a 419 error (unknown status). Does anyone know what's wrong?
(I'm using laravel 8)
I agree with #ElektaKode that the issue is likely due to lack of csrf token.
In order to disable CSRF middleware while testing,
switch off CSRF token for this route at /app/Http/Midddleware/VerifyCsrfToken.php, by updating:
protected $except = [ 'your-route-url' ];
Then you can use api authentication to follow it up.
The simplest way to use api authentication, follow this doc,
The other ways are either using Laravel passport or using jwt for api.(both will consume more time to set up, as you are using for testing using api authentication is your go to method.)
Usually in Laravel, 419 Page Expired error comes from CSRF middleware meaning there was a failure while validating CSRF token. Add your CSRF token to your test request or consider disabling CSRF middleware while testing.
Post Request with Laravels HTTP Client
$test = Http::post(route('users.leads.store', ['user' => $user->id]), [
"company_name" => "TESTCOMPANY",
"place_id" => null,
"street" => "MÜHLENKAMP 3",
"zip" => "49685",
"city" => "BÜHREN",
"title" => null,
"contact_name" => "FABIANLUKASSEN",
"additional_contacts" => null,
"phone1" => "+49 163 3006603",
"phone2" => null,
"email" => "FABIANLUKASSEN#TESTEN.DE",
"category" => "Hotel",
"sub_category" => null,
"website" => "www.fabianlukassen.de",
"status" => 1,
"expert_status" => 0,
"coordinates" => null,
"expert_id" => 1,
"agent_id" => null,
"blocked" => 0,
"important_note" => null,
]);
Route
Route::apiResource('users.leads', UserLeadController::class);
Store Method in the UserLeadController
public function store(User $user, CreateLeadRequest $request)
{
//TODO: Relocate validation to request class
if(!UserLeadController::isPhone("test", $request->phone1)) {
abort(400, "Keine gültige Telefonnummer!");
return;
}
if(!UserLeadController::isPhoneNumberUnique("test", $request->phone1)) {
abort(400, "Die Telefonnummer existiert bereits!");
return;
}
/**
* The logged in User
* #var User $agent
*/
$agent = Auth::user();
$phoneUtil = PhoneNumberUtil::getInstance();
$lead = new Lead();
$lead->fill($request->except(['appointment_end', 'appointment_comment']));
// Leads created by experts will be blocked
if ($user->id === $agent->id) {
$lead->blocked = true;
}
$numberProto = $phoneUtil->parse($lead->phone1, 'DE');
$lead->phone1 = $phoneUtil->format($numberProto, PhoneNumberFormat::INTERNATIONAL);
try {
$lead->save();
} catch (QueryException $e) {
//$message = 'Lead besteht bereits.';
//return Response::json(['errors' => $message], 422);
abort(422, "Lead besteht bereits!");
return;
}
if ($request->closed_until) {
$lead->closed_until = Carbon::create($request->closed_until);
$event_end = $request->appointment_end
? Carbon::parse($request->appointment_end)
: Carbon::parse($request->closed_until)->addMinutes(90);
$lead->calendarEvents()->save(new CalendarEvent([
'body' => $request->appointment_comment ?? "Wurde von {$this->roleDescriptor($agent->roles)}" . $agent->name . " angelegt.",
'type' => CalendarEventType::CALLCENTER_APPOINTMENT,
'event_begin' => $lead->closed_until,
'event_end' => $event_end,
]));
$lead->status = LeadState::APPOINTMENT;
$lead->expert_status = LeadExpertAcceptance::ACCEPTED;
} else {
$lead->status = LeadState::OPEN;
}
if (isset($request->agent)) {
$lead->agent_id = $request->agent;
}
try {
$user->leads()->save($lead);
$lead->comments()->save(new Comment([
'body' => "Wurde von {$this->roleDescriptor($agent->roles)}" . $agent->name . " angelegt.",
'user_id' => $agent->id,
'commentable_type' => 'lead',
'commentable_id' => $lead->id,
'reason' => 'CREATED',
'date' => now('Europe/Berlin'),
]));
if ($request->closed_until) {
$lead->comments()->save(new Comment([
'body' => "Termin wurde von {$this->roleDescriptor($agent->roles)}" . $agent->name . " vereinbart.",
'user_id' => $agent->id,
'commentable_type' => 'lead',
'commentable_id' => $lead->id,
'reason' => 'APPOINTMENT',
'date' => now('Europe/Berlin')->addMinute(),
]));
}
} catch (QueryException $e) {
//not sure if this works
$message = $e->getMessage();
abort(400, $message);
return;
}
if (empty($message)) {
return Response::json(['message' => 'Lead saved', 'lead' => new LeadSingleResource($lead)]);
} else {
return Response::json(compact('message'), 500);
}
}
//TODO: relocate function to rule object
protected static function isPhoneNumberUnique($attribute, $value) {
$withSpace = PhoneFormatter::formatInternational($value);
$withoutSpace = preg_replace('/ /', '', $withSpace);
$protos = [$withSpace, $withoutSpace]; // Necessary because legacy (25.06.2020).
$booleanTest = Company::query()->whereIn('phone', $protos)->doesntExist()
|| Lead::query()->whereIn('phone1', $protos)->orWhereIn('phone2', $protos)->doesntExist();
return $booleanTest;
}
//TODO: relocate function to rule object
protected static function isPhone($attribute, $value) {
if (!$value) {
return false;
}
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
$test = $phoneUtil->isValidNumber($phoneUtil->parse($value, 'DE'));
return $test;
}
fillable variable in the Lead Model
protected $fillable = [
'company_name',
'place_id',
'street',
'zip',
'city',
'title',
'contact_name',
'additional_contacts',
'phone1',
'phone2',
'email',
'category',
'sub_category',
'website',
'status',
'expert_status',
'coordinates',
'expert_id',
'agent_id',
'blocked',
'important_note'
];
As mentioned before, I receive a 200 OK status. Also, in a Vue.js component, I have done the following axios post request, which also just works fine.
axios
.post(`/api/users/${this.user_id}/leads`, {
"company_name": this.companyName,
"zip": this.zipCode,
"city": this.city,
"street": this.streetAndHouseNumber,
"contact_name": this.contactPartner,
"phone1": this.contactPartnerPhoneNumber,
"email": this.contactPartnerEmail,
"website": this.website,
"category": this.category,
"closed_until": this.appointmentStart,
"appointment_end": this.appointmentEnd,
"appointment_comment": this.comment,
//not used but needed (don't know the purpose)
"additional_contacts": "",
"phone2": "",
"sub_category": "",
"expert_status":this.expert_status,
}).then(() => {
window.location.href = this.routeSuccess;
}).catch((error) => {
this.showErrorAlert = true;
this.errorAlertMessage = error.response.data.message;
});
}

Auth::attempt() Manually Authenticating Users based on NULL condition | Laravel | Passport

I am creating an application based on Laravel 5.8. I want to manually authentication users based on some checks, But these checks or fields have some null values or not null values.
I follow the official documentation Link
Instead of checking like this
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// The user is active, not suspended, and exists.
}
I want to check if some fields that are not null like
if (Auth::attempt(['email' => $email, 'password' => $password, 'activate_on' => 'SomeDateTimeValue Or Not Null' ])) {
}
So it means if the user has some activate_on fields value which should not Null then the Auth::attempt should return true otherwise false.
You can do it by adding your implementation of the UserProvider interface, but that's a lot of work.
I think the easiest way is to do it in two steps.
// first get the user by email
$user = User::whereEmail($email)->first();
if($user->activate_on && Auth::attempt(['email' => $email, 'password' => $password])
{
// logged in
}
I do not believe what you are asking is directly possible. If you take a look at the retrieveByCredentials() method which is called during the attempt() process, the query builder is only set up to accept a value where($key, $value) or an array of values whereIn($key, $value) to conditionally query the user.
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials) ||
(count($credentials) === 1 &&
array_key_exists('password', $credentials))) {
return;
}
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->newModelQuery();
foreach ($credentials as $key => $value) {
if (Str::contains($key, 'password')) {
continue;
}
if (is_array($value) || $value instanceof Arrayable) {
$query->whereIn($key, $value);
} else {
$query->where($key, $value);
}
}
return $query->first();
}
EDIT:
Sample helper function:
if (!function_exists('attempt')) {
function attempt($credentials, $dates = [], $remember = false)
{
$user = User::where('email',$credentials['email'])->first();
// if a date is null return false
foreach ((array)$dates as $date) {
if (is_null($user->{$date})) {
return false;
}
}
return Auth::attempt($credentials, $remember);
}
}
Usage:
// single date
if (attempt(['email' => $email, 'password' => $password],'activate_on')) {
// ...
}
// array of dates
if (attempt(['email' => $email, 'password' => $password],['activate_on','approve_on'])) {
// ...
}
// no date
if (attempt(['email' => $email, 'password' => $password])) {
// ...
}

Post Method with Guzzle doesn't work / Laravel 5

I want to execute a scheduled task with laravel, which make a post with a single param.
I already checked with Postman my POST, so, I just have to hit myurl.com with param ID=188888 for instance. I get it working with postman.
So, first, I'm making the Laravel command : check:time, which just performs the post, and then, once I get it working, I will schedule it.
Thing is it appears commands is doing nothing, and I have no error logs.
So, really, it is not so easy to debug it...
Here is my Command Code:
class CheckTime extends Command
{
protected $signature = 'check:time {empId}';
protected $description = 'Check your time';
public function handle()
{
$client = new Client;
$numEmp = $this->argument('empId');
$response = $client->post('http://example.com/endpoint.php', ['ID' => $numEmp]);
var_dump($response);
}
}
When I print $response, I get:
class GuzzleHttp\Psr7\Response#495 (6) {
private $reasonPhrase =>
string(2) "OK"
private $statusCode =>
int(200)
private $headers =>
array(6) {
'date' =>
array(1) {
[0] =>
string(29) "Wed, 01 Jun 2016 00:17:52 GMT"
}
'server' =>
array(1) {
[0] =>
string(22) "Apache/2.2.3 (Red Hat)"
}
'x-powered-by' =>
array(1) {
[0] =>
string(10) "PHP/5.3.15"
}
'content-length' =>
array(1) {
[0] =>
string(3) "146"
}
'connection' =>
array(1) {
[0] =>
string(5) "close"
}
'content-type' =>
array(1) {
[0] =>
string(24) "text/html; charset=UTF-8"
}
}
private $headerLines =>
array(6) {
'Date' =>
array(1) {
[0] =>
string(29) "Wed, 01 Jun 2016 00:17:52 GMT"
}
'Server' =>
array(1) {
[0] =>
string(22) "Apache/2.2.3 (Red Hat)"
}
'X-Powered-By' =>
array(1) {
[0] =>
string(10) "PHP/5.3.15"
}
'Content-Length' =>
array(1) {
[0] =>
string(3) "146"
}
'Connection' =>
array(1) {
[0] =>
string(5) "close"
}
'Content-Type' =>
array(1) {
[0] =>
string(24) "text/html; charset=UTF-8"
}
}
private $protocol =>
string(3) "1.1"
private $stream =>
class GuzzleHttp\Psr7\Stream#493 (7) {
private $stream =>
resource(311) of type (stream)
private $size =>
NULL
private $seekable =>
bool(true)
private $readable =>
bool(true)
private $writable =>
bool(true)
private $uri =>
string(10) "php://temp"
private $customMetadata =>
array(0) {
}
}
}
I checked that $numEmp is OK, also, I printed $response and everything seems to be fine
As I said, I also execute the post with Postman, and it works, so, I don't really understand what's going on...
Any idea??
As #Denis Mysenko wisely advised, I tried:
$response->getBody()->getContents()
and found out that my post was getting a SQL error message.
Solution: to pass form parameters with guzzle, you have to pass it like that:
response = $client->post('http://example.com/endpoint.php', [
'form_params' => [
'ID' => $empId,
...
]
]);

Laravel error: 'preg_replace(): Parameter mismatch' on multiple file upload insert

I've got a form which allows for multiple entries into a database. Each of these rows contains a file upload field.
The fields are created as follows:
{{ Form::select('revision[]', ['0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6'], '0', ['class' => 'form-control artwork-revision']); }}
{{ Form::text('product[]', false, ['class' => 'form-control artwork-product', 'placeholder' => 'Please enter the product name']) }}
{{ Form::file('file[]', ['class' => 'artwork-file']) }}
My controller has a foreach loop to enter each row into the database but when I run it, I get the following error message: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
The code works when it's adapted for a single file upload (i.e. without the foreach loop and with only one row to be inserted, fields created without the square brackets)
How can I get past this error and enter the info into the database?
Here is the foreach loop in my controller and a var_dump of the object.
Controller foreach loop:
$files = Input::file('file');
foreach($files as $file) {
// it's a new artwork row
$artwork = new Artwork;
// get the vars
$artwork->job_id = Input::get('job_id');
$artwork->revision = Input::get('revision');
$artwork->product = Input::get('product');
// it's pending
$artwork->status = 'P';
// sort the filename...
$filename = $file->getClientOriginalName();
$file = $file->move(base_path() . '/public/artwork/' . Input::get('job_id'), $filename);
// ...and put it in the $artwork object
$artwork->filename = 'artwork/' . $artwork->job_id . '/' . $filename;
// save it
$artwork->save();
}
var_dump($artwork) output - note that only one image filename is showing in this rather than two:
object(Artwork)#243 (21) {
["dates":protected]=>
array(1) {
[0]=>
string(10) "deleted_at"
}
["fillable":protected]=>
array(6) {
[0]=>
string(6) "job_id"
[1]=>
string(8) "filename"
[2]=>
string(6) "status"
[3]=>
string(8) "revision"
[4]=>
string(7) "product"
[5]=>
string(6) "reason"
}
["table":protected]=>
string(8) "artworks"
["connection":protected]=>
NULL
["primaryKey":protected]=>
string(2) "id"
["perPage":protected]=>
int(15)
["incrementing"]=>
bool(true)
["timestamps"]=>
bool(true)
["attributes":protected]=>
array(5) {
["job_id"]=>
string(1) "5"
["revision"]=>
array(2) {
[0]=>
string(1) "0"
[1]=>
string(1) "0"
}
["product"]=>
array(2) {
[0]=>
string(15) "Twist USB Drive"
[1]=>
string(19) "Eco Twist USB Drive"
}
["status"]=>
string(1) "P"
["filename"]=>
string(24) "artwork/5/12345-test.jpg"
}
["original":protected]=>
array(0) {
}
["relations":protected]=>
array(0) {
}
["hidden":protected]=>
array(0) {
}
["visible":protected]=>
array(0) {
}
["appends":protected]=>
array(0) {
}
["guarded":protected]=>
array(1) {
[0]=>
string(1) "*"
}
["touches":protected]=>
array(0) {
}
["observables":protected]=>
array(0) {
}
["with":protected]=>
array(0) {
}
["morphClass":protected]=>
NULL
["exists"]=>
bool(false)
["forceDeleting":protected]=>
bool(false)
}
This is my new 'store' controller that solves the issue:
$artwork = new Artwork;
// standard bits
$artwork->job_id = Input::get('job_id');
$artwork->status = 'P';
// variables
$artwork->revision = Input::get('revision');
$artwork->product = Input::get('product');
$artwork->file = Input::file('file');
// count how many pieces of artwork are being uploaded (this could be any field)
$count = count($artwork->revision);
/* multi-file upload */
$i = 0;
// process each piece
foreach($artwork as $a) {
while($count > $i) {
// it's a new piece of artwork
$a = new Artwork;
// standard bits to object
$a->job_id = $artwork->job_id;
$a->status = $artwork->status;
// revision and product name to object
$a->revision = $artwork->revision[$i];
$a->product = $artwork->product[$i];
// get the file and move it
$file = $artwork->file[$i];
$filename = $file->getClientOriginalName();
$movefile = $file->move(base_path() . '/public/artwork/' . $artwork->job_id, $filename);
// filename to object
$a->filename = $filename;
// save the object to db
$a->save();
// add 1 to the count
$i++;
}
}
return Redirect::route('jobs.index');
I think you can't even select multiple files. Replace your file field with this one it has multiple attribute set to true which will allow multiple files to be selected at once and returns an array of files.
{{ Form::file('file[]', ['class' => 'artwork-file','multiple' => true]) }}

Resources