0

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)

  • Does this answer your question? [Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired](https://stackoverflow.com/questions/52583886/post-request-in-laravel-error-419-sorry-your-session-419-your-page-has-exp) – miken32 Nov 23 '20 at 15:56

3 Answers3

0

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.

cednore
  • 874
  • 4
  • 20
0

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.)

bhucho
  • 3,903
  • 3
  • 16
  • 34
  • Thanks, this worked, I now get a 200 OK status. However, theres is no database entry made by the post request. Any suggestions? – Fabian Lukassen Nov 25 '20 at 10:21
  • show the code for where you want to do database entry, how are you recieving the response, what are you getting in `$response->json() `, also please accept the answer, keeps me motivated to help others on stackoverflow – bhucho Nov 25 '20 at 10:26
0

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;
        });
  }
  • one thing you can do is debug the code in store using returns, like check first if $request is recieved in store method by returning $return in the response in just first line you will know where the error lies, also this is a answer block, you can't add code to be asked here, I would suggest to edit the question, as you are a new user your answers are reviewed so there might be chance that it can be removed – bhucho Nov 25 '20 at 11:26