This is some wierd situation in which I am there right now like I have one object
$this->remitter;
if I dump this I get this
App\Models\IpayAppBc\Remitter {#1960
#connection: "ipay_app_bc__write"
+table: "remitter"
+timestamps: false
#primaryKey: "id"
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:15 [
"id" => 15016478
"name" => "ASKHSYA"
"name_last" => ""
"dob" => null
"mobile" => "1234567"
"limit_expiry" => "{"PB":"202212"}"
"address" => "PANCHKULA PANCHKULA HARYANA"
"city" => "PANCHKULA"
"pincode" => "134117"
"state" => "HARYANA"
"two_factor" => 0
"status" => 0
"otp_status" => 2
"paytm_key" => "h00097ea42dc-a6ed-42bc-b2cf-3b6a876f878b"
"ab_kyc" => 0
]
#original: array:15 [
"id" => 15016478
"name" => "ASKHSYA"
"name_last" => ""
"dob" => null
"mobile" => "9946617986"
"limit_expiry" => "{"PB":"202212"}"
"address" => "PANCHKULA PANCHKULA HARYANA"
"city" => "PANCHKULA"
"pincode" => "134117"
"state" => "HARYANA"
"two_factor" => 0
"status" => 0
"otp_status" => 2
"paytm_key" => "h00097ea42dc-a6ed-42bc-b2cf-3b6a876f878b"
"ab_kyc" => 0
]
Now I did this
$remitterDetails = $this->remitter;
$remitterDetails->beneficiaries = $remitterDetails->beneficiaries->take(50)->map(function ($beneficiary) {
return [
'id' => $beneficiary->bene_id,
'name' => $beneficiary->name,
'account' => $beneficiary->account,
'ifsc' => $beneficiary->ifsc,
'bank' => $beneficiary->bank,
'verificationDt' => $beneficiary->last_success_dt,
];
});
Now the confusing part is this mapping changed my $this->remitter too
after dumping $this->remitter again i get this
App\Models\IpayAppBc\Remitter {#1960
#connection: "ipay_app_bc__write"
+table: "remitter"
#attributes: array:16 [
"id" => 15016478
"name" => "ASKHSYA"
"name_last" => ""
"dob" => null
"mobile" => "1234567"
"limit_expiry" => "{"PB":"202212"}"
"address" => "PANCHKULA PANCHKULA HARYANA"
"city" => "PANCHKULA"
"pincode" => "134117"
"state" => "HARYANA"
"two_factor" => 0
"status" => 0
"otp_status" => 2
"paytm_key" => "h00097ea42dc-a6ed-42bc-b2cf-3b6a876f878b"
"ab_kyc" => 0
"beneficiaries" => Illuminate\Support\Collection {#1956
#items: array:2 [
0 => array:6 [
"id" => "898ddaeff5a54bf2f05a3ce00f5cd13a"
"name" => "DUMMY"
"account" => "37893810436"
"ifsc" => "SBIN0000001"
"bank" => "STATE BANK OF INDIA"
"verificationDt" => "2022-12-01 16:58:57"
]
1 => array:6 [
"id" => "c647579b5881ffc39cb2ffb1fc600634"
"name" => "MRAN DW"
"account" => "3789381043"
"ifsc" => "SBIN0000001"
"bank" => "STATE BANK OF INDIA"
"verificationDt" => null
]
]
#escapeWhenCastingToString: false
}
I am just assuming why this happened is there any referencing happening because as per my knowledge this only happens when I use referencing to any variable ?
any information on this please
Thanks
i am using laravel framework ,for testing API's i am using postman.i have one registration api which receives an input and storing the data based on some checks ,it's not passing the condition of $request->has('phone') can you please help me how to resolve this issue..?
UserRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserRequest extends FormRequest
{
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'phone' =>'required|integer'
];
}
}
controller.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UserRequest;
use App\Models\User;
use App\Transformers\UserTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use JWTAuth;
class UserController extends Controller
{
public function register(UserRequest $request){
if($request->has('phone')){
// some logic
}
if($request->has('user_name'){
//some logic
}
}
CURL Request
curl --location --request POST 'http://127.0.0.1:8000/api/register' \
--header 'Cookie: XSRF-TOKEN=eyJpdiI6InlXRkRCSVJyQ2xpWDA3WnZmY3BnMXc9PSIsInZhbHVlIjoiOGM5TnJkUTNHRjBtZk81ZjE2dEo4L29YZ3lkbnVWTWdidmlQb0N0Z29tSERHU1EvaXBXbWlLa3RsdTljVzlrUVNjZU9xSDJPRzJQUXJjSDE5UThCYmtVMDlGV1hONVg2N0s2bWY4bGY2NEhidVczYXlPZVNRSS9zNjlCNWJ0WGIiLCJtYWMiOiI4MjczYzE1ZTAxNDJmYmNiYTI4OTIzZjlhYWIxYzJkMjZmNzk1NDFiOGZlODBiZjFmYmY2NzdjNjNiMTZmY2QyIiwidGFnIjoiIn0%3D; laravel_session=eyJpdiI6IkRyUTRVN0RSUStBK2pmakRnUDFmbmc9PSIsInZhbHVlIjoiWlNZWXVhVWlOSXhXOEhoNjNUQktyb1BEaEQvekhaWFphMVk5NVZKaFdzZ2VtL0FqVUlUMXJ4THJLSjdkZHhmYTA1eUUyeVNhdUp6UncwczN2OGZDcTVrOS9WVzJQRUxHbm40cnE3ZjJkd2ZZY0J1UlgvQWdyWTdJMVVnejY0cDgiLCJtYWMiOiJmYzdhZGMzZmY3MWRiYTc1YjZjZThjZWFiMzk0ZTBhMjM3ZGU3OGFjYTJmN2Q3MmU3ZDVlMjYwZTUyM2ZjYjVkIiwidGFnIjoiIn0%3D' \
--form 'phone="56788988"'
dd($request)
Illuminate\Http\Request {#43
#json: null
#convertedFiles: null
#userResolver: Closure($guard = null) {#262
class: "Illuminate\Auth\AuthServiceProvider"
this: Illuminate\Auth\AuthServiceProvider {#150 …}
use: {
$app: Illuminate\Foundation\Application {#2 …}
}
file: "/home/payarc/SHARE-COST/lemonpeak_sharecost/vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php"
line: "96 to 98"
}
#routeResolver: Closure() {#270
class: "Illuminate\Routing\Router"
this: Illuminate\Routing\Router {#26 …}
use: {
$route: Illuminate\Routing\Route {#250 …}
}
file: "/home/payarc/SHARE-COST/lemonpeak_sharecost/vendor/laravel/framework/src/Illuminate/Routing/Router.php"
line: "691 to 693"
}
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#45
#parameters: []
}
+request: Symfony\Component\HttpFoundation\InputBag {#44
#parameters: array:1 [
"phone" => "7901002572"
]
}
+query: Symfony\Component\HttpFoundation\InputBag {#51
#parameters: []
}
+server: Symfony\Component\HttpFoundation\ServerBag {#47
#parameters: array:27 [
"DOCUMENT_ROOT" => "/home/payarc/SHARE-COST/lemonpeak_sharecost/public"
"REMOTE_ADDR" => "127.0.0.1"
"REMOTE_PORT" => "37410"
"SERVER_SOFTWARE" => "PHP 7.4.16 Development Server"
"SERVER_PROTOCOL" => "HTTP/1.1"
"SERVER_NAME" => "127.0.0.1"
"SERVER_PORT" => "8000"
"REQUEST_URI" => "/api/register"
"REQUEST_METHOD" => "POST"
"SCRIPT_NAME" => "/index.php"
"SCRIPT_FILENAME" => "/home/payarc/SHARE-COST/lemonpeak_sharecost/public/index.php"
"PATH_INFO" => "/api/register"
"PHP_SELF" => "/index.php/api/register"
"HTTP_USER_AGENT" => "PostmanRuntime/7.28.4"
"HTTP_ACCEPT" => "*/*"
"HTTP_CACHE_CONTROL" => "no-cache"
"HTTP_POSTMAN_TOKEN" => "a67d63c4-d560-4867-a066-5d9d81c38e99"
"HTTP_HOST" => "127.0.0.1:8000"
"HTTP_ACCEPT_ENCODING" => "gzip, deflate, br"
"HTTP_CONNECTION" => "keep-alive"
"CONTENT_TYPE" => "multipart/form-data; boundary=--------------------------727143787238577144588277"
"HTTP_CONTENT_TYPE" => "multipart/form-data; boundary=--------------------------727143787238577144588277"
"HTTP_COOKIE" => "XSRF-TOKEN=eyJpdiI6ImtJMkhNOXBvbjZYMzNFejRNbUpsemc9PSIsInZhbHVlIjoiT21ScElGOUprdnVVY2MxMFpreEVCVTlzS2RGM09Ed1ZQWk1IYnA3L1ZjK2ZoOXA0eUxwVSthRG53cWRydmVNZEJGNlVDUmM0V1NZTU1VOWNraE9yRWE3dGhLQXFubVZoczZ5TFgzSTlXK2UvUlRsTFpxNzgxeHE1d2loRXdWTnYiLCJtYWMiOiIzNGYyYTZjMWE2NDIxNjYxYTI1Nzc0YTI1OGIxMGRlNDhlOWEyZGVkZmI2ODNiM2M2ZmI4MTM2MjAxZjM0YTg0IiwidGFnIjoiIn0%3D; laravel_session=eyJpdiI6IkRqWXVYakNaRXVZdCtpUUlmMExZd1E9PSIsInZhbHVlIjoiZmJsQzVRWEhVM0IwYWVVeTZEMnRnQ3Qva1B6NWZLMkJYZWgvcHZONVYwd3VuZnN6cGYzZVJRMzdsUVZvSlJDR01jd1RxZHRNMCtRY3doZDRFZzlmc1MycTlvbDNKTUcyaE9wb2lZZDJqMTJKNmxZVjRGNVM1YzE5cHhjRklvU3MiLCJtYWMiOiI3MmU1OWJhOGEwNTFmYmE2OWQ4OWI1OGMzYTFiMDAyN2NlNWViY2MyMzBmNmIxODAyZThlODA3Y2NjZTYyYjRlIiwidGFnIjoiIn0%3D"
"CONTENT_LENGTH" => "170"
"HTTP_CONTENT_LENGTH" => "170"
"REQUEST_TIME_FLOAT" => 1655210722.3332
"REQUEST_TIME" => 1655210722
]
}
+files: Symfony\Component\HttpFoundation\FileBag {#48
#parameters: []
}
+cookies: Symfony\Component\HttpFoundation\InputBag {#46
#parameters: array:2 [
"XSRF-TOKEN" => "eyJpdiI6ImtJMkhNOXBvbjZYMzNFejRNbUpsemc9PSIsInZhbHVlIjoiT21ScElGOUprdnVVY2MxMFpreEVCVTlzS2RGM09Ed1ZQWk1IYnA3L1ZjK2ZoOXA0eUxwVSthRG53cWRydmVNZEJGNlVDUmM0V1NZTU1VOWNraE9yRWE3dGhLQXFubVZoczZ5TFgzSTlXK2UvUlRsTFpxNzgxeHE1d2loRXdWTnYiLCJtYWMiOiIzNGYyYTZjMWE2NDIxNjYxYTI1Nzc0YTI1OGIxMGRlNDhlOWEyZGVkZmI2ODNiM2M2ZmI4MTM2MjAxZjM0YTg0IiwidGFnIjoiIn0="
"laravel_session" => "eyJpdiI6IkRqWXVYakNaRXVZdCtpUUlmMExZd1E9PSIsInZhbHVlIjoiZmJsQzVRWEhVM0IwYWVVeTZEMnRnQ3Qva1B6NWZLMkJYZWgvcHZONVYwd3VuZnN6cGYzZVJRMzdsUVZvSlJDR01jd1RxZHRNMCtRY3doZDRFZzlmc1MycTlvbDNKTUcyaE9wb2lZZDJqMTJKNmxZVjRGNVM1YzE5cHhjRklvU3MiLCJtYWMiOiI3MmU1OWJhOGEwNTFmYmE2OWQ4OWI1OGMzYTFiMDAyN2NlNWViY2MyMzBmNmIxODAyZThlODA3Y2NjZTYyYjRlIiwidGFnIjoiIn0="
]
}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#49
#headers: array:10 [
"user-agent" => array:1 [
0 => "PostmanRuntime/7.28.4"
]
"accept" => array:1 [
0 => "*/*"
]
"cache-control" => array:1 [
0 => "no-cache"
]
"postman-token" => array:1 [
0 => "a67d63c4-d560-4867-a066-5d9d81c38e99"
]
"host" => array:1 [
0 => "127.0.0.1:8000"
]
"accept-encoding" => array:1 [
0 => "gzip, deflate, br"
]
"connection" => array:1 [
0 => "keep-alive"
]
"content-type" => array:1 [
0 => "multipart/form-data; boundary=--------------------------727143787238577144588277"
]
"cookie" => array:1 [
0 => "XSRF-TOKEN=eyJpdiI6ImtJMkhNOXBvbjZYMzNFejRNbUpsemc9PSIsInZhbHVlIjoiT21ScElGOUprdnVVY2MxMFpreEVCVTlzS2RGM09Ed1ZQWk1IYnA3L1ZjK2ZoOXA0eUxwVSthRG53cWRydmVNZEJGNlVDUmM0V1NZTU1VOWNraE9yRWE3dGhLQXFubVZoczZ5TFgzSTlXK2UvUlRsTFpxNzgxeHE1d2loRXdWTnYiLCJtYWMiOiIzNGYyYTZjMWE2NDIxNjYxYTI1Nzc0YTI1OGIxMGRlNDhlOWEyZGVkZmI2ODNiM2M2ZmI4MTM2MjAxZjM0YTg0IiwidGFnIjoiIn0%3D; laravel_session=eyJpdiI6IkRqWXVYakNaRXVZdCtpUUlmMExZd1E9PSIsInZhbHVlIjoiZmJsQzVRWEhVM0IwYWVVeTZEMnRnQ3Qva1B6NWZLMkJYZWgvcHZONVYwd3VuZnN6cGYzZVJRMzdsUVZvSlJDR01jd1RxZHRNMCtRY3doZDRFZzlmc1MycTlvbDNKTUcyaE9wb2lZZDJqMTJKNmxZVjRGNVM1YzE5cHhjRklvU3MiLCJtYWMiOiI3MmU1OWJhOGEwNTFmYmE2OWQ4OWI1OGMzYTFiMDAyN2NlNWViY2MyMzBmNmIxODAyZThlODA3Y2NjZTYyYjRlIiwidGFnIjoiIn0%3D"
]
"content-length" => array:1 [
0 => "170"
]
]
#cacheControl: array:1 [
"no-cache" => true
]
}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/api/register"
#requestUri: "/api/register"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: null
#locale: null
#defaultLocale: "en"
-preferredFormat: null
-isHostValid: true
-isForwardedValid: true
-isSafeContentPreferred: null
basePath: ""
format: "html"
}
In postman headers you have to add Accept as a application\json and select as form-data in body section
After that please verify your passing the has check request key has matched to the form-data one.let me know if this will work
Under Rules of your userRequest.php, u set integer validation but not defined the integer length. for example, if you processing the integer value between 1 to 10, do this
public function rules()
{
return [
'phone' =>'required|integer|between:1,10'
];
}
or you can change
public function register(UserRequest $request){
if($request->has('phone')){
// some logic
}
if($request->has('user_name'){
//some logic
}
to
public function register(Request $request){
if($request->has('phone')){
// some logic
}
if($request->has('user_name'){
//some logic
}
to get your value, but it bypasses the validation
I want to compare two columns of a collection.I don't want to do this in db level, only in collection level.
I have a collection like this (I returned it in array model for readability)
array:3 [
0 => array:5 [
"total_amount" => 200000.0
"admin_max_amount" => "200000000"
]
1 => array:5 [
"total_amount" => 100000.0
"admin_max_amount" => "200000000"
]
2 => array:5 [
"total_amount" => 100000.0
"admin_max_amount" => "0"
]
]
I want to get first of them where total_amount > admin_max_amount.
Here is a more 'Laravel' way to do it:
$items = collect([
[
"total_amount" => 200000.0,
"admin_max_amount" => "200000000",
],
[
"total_amount" => 100000.0,
"admin_max_amount" => "200000000",
],
[
"total_amount" => 100000.0,
"admin_max_amount" => "0",
],
]);
$result = $items->first(function ($item)
{
return (float)$item['total_amount'] > (float)$item['admin_max_amount'];
});
dump($result);
I managed to create a Customer in ChargeBee but I don't know how to access each of its values.
To receive the information I use the following code, it works perfect for me ...
ChargeBee_Environment::configure("mysite-test","test_afhjsfslfsfslk438493sshgeh");
$result = ChargeBee_Customer::retrieve("16HHGDGJslfksds");
$customer = $result->customer();
$card = $result->card();
By doing a dd($result) I get the following:
ChargeBee_Result {#356 ▼
-_response: array:1 [▼
"customer" => array:22 [▼
"id" => "16HHGDGJslfksds"
"first_name" => "User"
"last_name" => "Test"
"email" => "user#mail.com"
"phone" => "555667788"
"auto_collection" => "on"
"net_term_days" => 0
"allow_direct_debit" => false
"created_at" => 1603420880
"taxability" => "taxable"
"updated_at" => 1603420880
"pii_cleared" => "active"
"resource_version" => 1603420880216
"deleted" => false
"object" => "customer"
"billing_address" => array:6 [▶]
"card_status" => "no_card"
"promotional_credits" => 0
"refundable_credits" => 0
"excess_payments" => 0
"unbilled_charges" => 0
"preferred_currency_code" => "USD"
]
]
-_responseObj: array:1 [▼
"customer" => ChargeBee_Customer {#358 ▶}
]
}
How can I get for example the id of this Customer??? Which in this case is 16HHGDGJslfksds
You can use this line:
$customerId = $result->customer()->id
class ExampleTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->base_url = config('app.url');
$response = $this->post($this->base_url . '/auth/login', [
'username' => 'root',
'password' => '123',
]);
// how to get the login session cookie?
}
public function testStep1()
{
// how to set the login session to this POST request?
$response = $this->post($this->base_url . '/step1', [
'attr_1' => 'foo',
'attr_2' => 'bar',
]);
...
}
public function testStep2()
{
// how to set the login session to this POST request?
$response = $this->post($this->base_url . '/step2', [
'attr_1' => 'abc',
'attr_2' => 'xyz',
]);
...
}
}
From the sample code above, what I want to achieve is testStep1 & testStep2 must in order (wizard to create something). Thus, I must maintain the same session.
Is it possible to achieve?
Edit 2018-07-10 14:51 UTC+8
I've tried the output after call the /auth/login, the value of $response->headers->getCookies() is
array:1 [
0 => Symfony\Component\HttpFoundation\Cookie {#940
#name: "XSRF-TOKEN"
#value: "eyJpdiI6IjQwUKxYnZlQ0J3N1B0Vkp4VjBEWVE9PSIsInZhbHVlIj782RKOUh2UFhONFwvaVRPUm56YkJ1ekxxSXlCTmtYSFNyRUF3NTdCTWhBMHhEQis1VVU0OUFcL3pKQUcybTFwQjdad1I1em02V1d4bVhDZWR2NFluUTlxdz09IiwibWFjIjoiZWRjYjk2NWI1MTU3YmJlMGEwMDdiNjNkYmVkMjBjMWU3NTRmZjE5NmMyM2EwOTZlNWJmZmYwMmRmYmExMWE1MSJ9"
#domain: null
#expire: 1531218886
#path: "/"
#secure: false
#httpOnly: false
-raw: false
-sameSite: null
}
]
and the value of $response is
Illuminate\Foundation\Testing\TestResponse {#843
+baseResponse: Illuminate\Http\RedirectResponse {#1040
#request: Illuminate\Http\Request {#856
#json: null
#convertedFiles: null
#userResolver: Closure {#916
class: "Illuminate\Auth\AuthServiceProvider"
this: Illuminate\Auth\AuthServiceProvider {#52 …}
parameters: {
$guard: {
default: null
}
}
use: {
$app: Illuminate\Foundation\Application {#19 …}
}
file: "./vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php"
line: "85 to 87"
}
#routeResolver: Closure {#860
class: "Illuminate\Routing\Router"
this: Illuminate\Routing\Router {#167 …}
use: {
$route: Illuminate\Routing\Route {#204 …}
}
file: "./vendor/laravel/framework/src/Illuminate/Routing/Router.php"
line: "527 to 529"
}
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#870
#parameters: []
}
+request: Symfony\Component\HttpFoundation\ParameterBag {#867
#parameters: array:2 [
"username" => "root"
"password" => "123"
]
}
+query: Symfony\Component\HttpFoundation\ParameterBag {#911
#parameters: []
}
+server: Symfony\Component\HttpFoundation\ServerBag {#871
#parameters: array:17 [
"SERVER_NAME" => "localhost.com"
"SERVER_PORT" => 80
"HTTP_HOST" => "localhost.com"
"HTTP_USER_AGENT" => "Symfony/3.X"
"HTTP_ACCEPT" => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
"HTTP_ACCEPT_LANGUAGE" => "en-us,en;q=0.5"
"HTTP_ACCEPT_CHARSET" => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
"REMOTE_ADDR" => "127.0.0.1"
"SCRIPT_NAME" => ""
"SCRIPT_FILENAME" => ""
"SERVER_PROTOCOL" => "HTTP/1.1"
"REQUEST_TIME" => 1531204718
"PATH_INFO" => ""
"REQUEST_METHOD" => "POST"
"CONTENT_TYPE" => "application/x-www-form-urlencoded"
"REQUEST_URI" => "/auth/login"
"QUERY_STRING" => ""
]
}
+files: Symfony\Component\HttpFoundation\FileBag {#878
#parameters: []
}
+cookies: Symfony\Component\HttpFoundation\ParameterBag {#869
#parameters: []
}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#913
#headers: array:6 [
"host" => array:1 [
0 => "localhost.com"
]
"user-agent" => array:1 [
0 => "Symfony/3.X"
]
"accept" => array:1 [
0 => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
]
"accept-language" => array:1 [
0 => "en-us,en;q=0.5"
]
"accept-charset" => array:1 [
0 => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
]
"content-type" => array:1 [
0 => "application/x-www-form-urlencoded"
]
]
#cacheControl: []
}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/auth/login"
#requestUri: "/auth/login"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: Illuminate\Session\EncryptedStore {#924
#encrypter: Illuminate\Encryption\Encrypter {#919
#key: b"A╦k>ú8f\x10─ÌÜ8ØýxK\x01²┬Íî·»├\x1A³0▒S┘Ì"
#cipher: "AES-256-CBC"
}
#id: "XPMgecNkwFHbZbujhiuEaBqgMqFTLIqsuIzyvXv"
#name: "laravel_cookie"
#attributes: array:11 [
"_token" => "5lcOcLk9AqvSlWyLdHMKba1lJQ1UqD2rBBVCSav"
"locale" => "en"
"_previous" => array:1 [
"url" => "http://localhost.com/auth/login"
]
"_flash" => array:2 [
"old" => []
"new" => []
]
"sess_user_id" => 123
"sess_user_firstname" => "Foo"
"sess_user_lastname" => "Bar"
"sess_role" => "admin"
"login_web_59ba36add234f940abcf014c987ea4e30989d" => 123
]
#handler: Symfony\Component\HttpFoundation\Session\Storage\Handler\NullSessionHandler {#925
-sessionName: null
-prefetchId: null
-prefetchData: null
-newSessionId: null
-igbinaryEmptyData: "\x00\x00\x00\x02\x14\x00"
}
#started: false
}
#locale: null
#defaultLocale: "en"
-isHostValid: true
-isForwardedValid: true
basePath: ""
format: "html"
}
#session: Illuminate\Session\EncryptedStore {#924}
#targetUrl: "http://localhost.com/dashboard"
+headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#1039
#computedCacheControl: array:2 [
"no-cache" => true
"private" => true
]
#cookies: array:1 [
"" => array:1 [
"/" => array:1 [
"XSRF-TOKEN" => Symfony\Component\HttpFoundation\Cookie {#940
#name: "XSRF-TOKEN"
#value: "eyJpdiI6IjVyVmRNSmlcL1dYK0VOdiwj8RxamZBPT0iLCJ2YWx1ZSI6IjNSQWFzcVllSEIrSYwZnNNbk1vZ1NERVc2UVdJeGs91D6UG5hNGlHUmRnendJOUVtUnA3Rnk0TnVLYmI5UnJXSTlZR3dxS0wxMElmOFlaWDMzdG9RPT0iLCJtYWMiOiI0ZTZlNTAwNjFkZWFkOTEwN2M1Y2EzMGRjOWMzMmU4NzEzNmM5NWU2MzhhODFjOGJkYTU0YmZlMTM3M2ExNmE3In0="
#domain: null
#expire: 1531219118
#path: "/"
#secure: false
#httpOnly: false
-raw: false
-sameSite: null
}
]
]
]
#headerNames: array:5 [
"cache-control" => "Cache-Control"
"date" => "Date"
"location" => "Location"
"content-type" => "Content-Type"
"set-cookie" => "Set-Cookie"
]
#headers: array:4 [
"cache-control" => array:1 [
0 => "no-cache, private"
]
"date" => array:1 [
0 => "Tue, 10 Jul 2018 06:38:38 GMT"
]
"location" => array:1 [
0 => "http://localhost.com/dashboard"
]
"content-type" => array:1 [
0 => "text/html; charset=UTF-8"
]
]
#cacheControl: []
}
#content: """
<!DOCTYPE html>\n
<html>\n
<head>\n
<meta charset="UTF-8" />\n
<meta http-equiv="refresh" content="0;url=http://localhost.com/dashboard" />\n
\n
<title>Redirecting to http://localhost.com/dashboard</title>\n
</head>\n
<body>\n
Redirecting to http://localhost.com/dashboard.\n
</body>\n
</html>
"""
#version: "1.1"
#statusCode: 302
#statusText: "Found"
#charset: null
+original: null
+exception: null
}
}
So obviously, the session cookie is not in $response->headers->getCookies(), and I don't use actingAs() is because after user successful login, will set a few session values, i.e. sess_user_id, sess_user_firstname, sess_user_lastname, sess_role...
For the first case I would just make a post request and check if the cookie is present or not.
$response = $this->post($this->base_url . '/auth/login', [
'username' => 'root',
'password' => '123',
]);
$response->assertCookieNotExpired($cookieName);
Note: you can get cookies from headers using. $response->headers->getCookies(); but I don't think we need them in our case.
Now we know our authentication works we can use Laravel actingAs helper method for authentication and then make requests as follows.
$user = // get your user.
$response = $this->actingAs($user)->post($this->base_url . '/step1', [
'attr_1' => 'foo',
'attr_2' => 'bar',
]);
Make all kinds of assertion you like (check for cookies, sessions whatever you like)
$response->assertSessionHas($key, $value);
Before we move to the third case you should know that it's better to test each section separately. In simple words your tests shouldn't depend on each other, so what we can do for the third case? We know our third case depends on the second and we have already the tested the previous processes. Now we just want to test if our third case is working or not. So why not we add the session values required for this request ourselves using Laravel helper withSession.
$response = $this->actingAs($user)
->withSession(['foo' => 'bar'])
->post($this->base_url . '/step2', [
'attr_1' => 'abc',
'attr_2' => 'xyz',
]);
Now you can again make assertions. Check list of all available assertions.
Install Mockery Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit
composer require mockery/mockery --dev
LoginController
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
// Get the currently authenticated user...
$user = Auth::user();
return redirect()->route('profile');
}else{
return redirect()->intended('loginform');
}
}
Example Test
public function testLoginSuccess()
{
$credential = [
'email' => 'xxx',
'password' => 'yyy'
];
Auth::shouldReceive('attempt')->once()->withAnyArgs()->andReturn(true);
Auth::shouldReceive('user')->once()->withAnyArgs()->andReturn(true);
$response = $this->post('/login',$credential);
$response->assertRedirect('/profile');
}
This example show you how to mock Auth Facades in unit test.
Auth::attempt return true
Auth::user return true
You can use Mockery to mock object as you want.
Check phpunit.xml, by default the value of SESSION_DRIVER is set 'array', change it to 'file'