Model binding doesn't retrieve model data - laravel

I have this route:
Route::delete('product/{product}/attachments/{attachment}', 'AttachmentsController#destroy');
public function destroy(Product $product, Attachment $attachment)
{
dd($product);
}
and dd shows:
App\Models\Product^ {#1059
#fillable: array:3 [
0 => "title"
1 => "section_id"
2 => "sortOrder"
]
#attributes: []
#original: []
... etc
}
I can't access model data such as $product->title it will return null, so I tried to change destory method to:
public function destroy($product, Attachment $attachment)
{
$product = Product::whereId($product)->firstOrFail();
dd($product);
}
and now I can access/see the model data:
"section_id" => 18
"title" => "test product"
"sortOrder" => 217645360
"created_at" => "2020-05-05 13:34:54"
"updated_at" => "2020-05-05 13:34:54"
]
#original: array:8 [
"id" => 18
"section_id" => 18
"title" => "test product"
"sortOrder" => 217645360
"created_at" => "2020-05-05 13:34:54"
"updated_at" => "2020-05-05 13:34:54"
]
Why doesn't the model binding work? I even tried to add
public function boot()
{
parent::boot();
Route::model('product', App\Models\Product::class);
}
I tried also to do: cache:clear route:clearand composer dumpautoload I cant find why the model binding doesn't work?

Related

Laravel: test response is different from real response

In a Laravel9 project:
Controller.php
// /api/auth/user
public function show (Request $request) {
$user = $request->user();
$user->makeVisible(['email', 'email_verified_at', 'social']);
return $user;
}
The social is a nullable json column
$table->json('social')->nullable();
// 'social' => '{"facebook": "1234567890", "twitter": "1234567890"}
the actual HTTP response is (which I've verified in PostMan)
{
"id": 11,
"name": "Test User",
"email": "test#example.com",
"social": null,
"email_verified_at": "2022-12-27T02:50:58.000000Z",
"created_at": "2022-12-27T02:50:58.000000Z",
"updated_at": "2022-12-27T02:50:58.000000Z"
}
But in the Feature Test
tests/Feature/Auth/User/ShowTest.php
public function test_show_current_user () {
$user = User::factory()->create();
$response = $this->actingAs($user)->get($this->api);
$response
->assertStatus(200)
->assertJson([
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'email_verified_at' => $user->email_verified_at->jsonSerialize(),
'social' => $user->social,
]);
}
This test will always fail since it can't find social in the $response
Once I dd() the $response, there is no social attribute at all:
update:
My User model (since so doesn't support <details>, I use code snippet to create a foldable code)
// the User model in Feature Test
App\Models\User^ {#4147 // tests/Feature/Auth/User/ShowTest.php
#connection: "sqlite"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: true
#escapeWhenCastingToString: false
#attributes: array:8 [
"name" => "Bettie Von"
"email" => "lhermiston#example.net"
"email_verified_at" => "2022-12-27 08:51:06"
"password" => "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi"
"remember_token" => "eMBMnyRei4"
"updated_at" => "2022-12-27 08:51:06"
"created_at" => "2022-12-27 08:51:06"
"id" => 1
]
#original: array:8 [
"name" => "Bettie Von"
"email" => "lhermiston#example.net"
"email_verified_at" => "2022-12-27 08:51:06"
"password" => "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi"
"remember_token" => "eMBMnyRei4"
"updated_at" => "2022-12-27 08:51:06"
"created_at" => "2022-12-27 08:51:06"
"id" => 1
]
#changes: []
#casts: array:2 [
"email_verified_at" => "datetime"
"social" => "array"
]
#classCastCache: []
#attributeCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: array:2 [
0 => "password"
1 => "remember_token"
]
#visible: []
#fillable: array:4 [
0 => "name"
1 => "email"
2 => "password"
3 => "social"
]
#guarded: array:1 [
0 => "*"
]
#rememberTokenName: "remember_token"
#accessToken: null
}
Why is the $response in the feature test different from the actual HTTP response?
And how can I pass the feature test?
I figured it out by adding a simple $user->refresh();
$user = User::factory()
->create();
$user->refresh(); // add this
$response = $this
->actingAs($user)
->get($this->api);
Thanks a lot to #KGG, #apokryfos, and #Abdel-aziz hassan for their help.

How to create a nested array from collection with parent IDs in laravel?

I want to create a nested array which maintain parent child relations
by using their parent_id.I want to make the following query results
into nested array.NB:I have used same table to keep all category data.
$catItems= ProductCategory::all()->toArray();
$source = array();
foreach($catItems as $key => $value) {
$source[$key] = $value;
}
the following method I applied to create nested array
$nested = array();
foreach ($source as &$s) {
if(is_null($s['parent_id']) ) {
// no parent_id so we put it in the root of the array
$nested[] = &$s;
}
else {
$pid = $s['parent_id'];
if ( isset($source[$pid])) {
// If the parent ID exists in the source array
// we add it to the 'children' array of the parent after initializing it.
if ( !isset($source[$pid]['children']) ) {
$source[$pid]['children'] = array();
}
$source[$pid]['children'][] = &$s;
}
}
}
If i do dd($source) i am getting the following output
array:3 [▼
0 => array:8 [▼
"id" => 5
"name" => "Electronics"
"status" => 1
"parent_id" => null
"created_by" => 1
"updated_by" => null
"created_at" => "2021-05-06T06:32:37.000000Z"
"updated_at" => "2021-05-06T06:32:37.000000Z"
]
1 => array:8 [▼
"id" => 6
"name" => "tv"
"status" => 1
"parent_id" => 5
"created_by" => 1
"updated_by" => null
"created_at" => "2021-05-06T06:33:00.000000Z"
"updated_at" => "2021-05-06T06:33:00.000000Z"
]
2 => array:8 [▼
"id" => 7
"name" => "Home appliances"
"status" => 1
"parent_id" => null
"created_by" => 1
"updated_by" => null
"created_at" => "2021-05-06T06:33:16.000000Z"
"updated_at" => "2021-05-06T06:33:16.000000Z"
]
]
If i do dd($nested) i am getting the only parent array like bellow :
array:2 [▼
0 => & array:8 [▼
"id" => 5
"name" => "Electronics"
"status" => 1
"parent_id" => null
"created_by" => 1
"updated_by" => null
"created_at" => "2021-05-06T06:32:37.000000Z"
"updated_at" => "2021-05-06T06:32:37.000000Z"
]
1 => & array:8 [▼
"id" => 7
"name" => "Home appliances"
"status" => 1
"parent_id" => null
"created_by" => 1
"updated_by" => null
"created_at" => "2021-05-06T06:33:16.000000Z"
"updated_at" => "2021-05-06T06:33:16.000000Z"
]
]
Create this function to access children in ProductCategory.php file:
public function children()
{
return $this->hasMany(ProductCategory::class, 'parent_id');
}
In your controller:
$cartItems = ProductCategory::with('children')->get();
If you want to get parent of any child category:
public function parent()
{
return $this->belongsTo(ProductCategory::class, 'parent_id');
}
You can get its parents like this
public function parent()
{
return $this->belongsTo(ProductCategory::class)->with('parent');
}

How to check if an object property of a collection is not empty (deep level) - Laravel

I have this collection of Product types
Illuminate\Database\Eloquent\Collection {#1388
#items: array:3 [
0 => App\Model\ProductType {
#attributes: array:7 [
"id" => 3
"type" => "GG"
"businessId" => 22
"created_at" => "2020-09-17 00:00:00"
"updated_at" => "2020-09-17 00:00:00"
]
}
1 => App\Model\ProductType {
#attributes: array:7 [
"id" => 1
"type" => "Personal Collection"
"businessId" => 22
"created_at" => "2020-09-17 00:00:00"
"updated_at" => "2020-09-17 00:00:00"
]
}
2 => App\Model\ProductType {
#attributes: array:7 [
"id" => 2
"type" => "Supplies"
"businessId" => 22
"created_at" => "2020-09-17 00:00:00"
"updated_at" => "2020-09-17 00:00:00"
]
}
And ProductType model has getProductsAttribute which has condition that products will be only included if it has variants and variants will we only included if its stocks is > 0
Here is my sample code:
$checkProductsWithVariants = Product::where('productTypeId', $this->id)->get();
$variantStocksCount = 0;
foreach ($checkProductsWithVariants as $product) {
$variantStocksCount += $product->variants->count();
}
$hasProduct = $variantStocksCount > 0 ? true : false;
Take note that i'm running this for every productType
My problem is if I have many product types and products. my code is slow.
I want to know if there's a way to check like this or something similar to avoid looping every single products just to check variant's stocks
ProductType::where('product.variants.stocks', '>', 0);

How to update alias column in Laravel

I want to update records in Postgresql DB and Laravel.
The problem is that alias columns are not in relation with the table, but I made them in first place:
message: "SQLSTATE[42703]: Undefined column: 7 ERROR: column "nivo600" of relation "meas_kanal" does not exist↵LINE 1: update "meas_kanal" set "recordtime" = $1, "nivo600" = $2, "...↵
The function in controller:
$student = Stamboliiski::where('recordtime', $request->get('kanal_id'))
->selectRaw('recordtime')
->selectRaw('max(formattedvalue) filter (where fullname = \'text 1\') as nivo600')
->selectRaw('max(formattedvalue) filter (where fullname = \'text 2\') as razhod600')
->update([
'recordtime' => $request->input('recordtime'),
'nivo600' => $request->input('formattedvalueN'),
'razhod600' => $request->input('formattedvalueR'),
])
->where(function ($query) {
$query->where('fullname', 'like', "text 1")
->orWhere('fullname', 'like', "text 2");
})
->groupBy('recordtime')
->orderBy('recordtime')
->first();
$success_output = '<div class="alert alert-success">The record is updated!</div>';
Model:
class Stamboliiski extends Model
{
protected $connection = 'stamboliiski';
protected $table = 'meas_kanal';
protected $fillable = ['fullname','formattedvalue','recordtime','qualitydesc','statedesc','author','id'];
}
Why?
EDIT 1 after comment of #Dimitri Mostrey:
$student = Stamboliiski::where('recordtime', $request->get('kanal_id'))
->selectRaw('recordtime')
->selectRaw('max(formattedvalue) filter (where fullname = \'text 1\') as nivo600')
->selectRaw('max(formattedvalue) filter (where fullname = \'text 2\') as razhod600')
->where(function ($query) {
$query->where('fullname', 'like', "text 1")
->orWhere('fullname', 'like', "text 2");
})
->groupBy('recordtime')
->orderBy('recordtime')
->first();
$student->recordtime = $request->get('recordtime');
$student->nivo600 = $request->get('formattedvalueN');
$student->razhod600 = $request->get('formattedvalueR');
$student->author = Auth::user()->name;
$student->save();
The error now is this:
message: "SQLSTATE[42703]: Undefined column: 7 ERROR: column "nivo600" of relation "meas_kanal" does not exist↵LINE 1: update "meas_kanal" set "nivo600" = $1, "razhod600" = $2, "a...↵ ^ (SQL: update "meas_kanal" set "nivo600" = 1.86, "razhod600" = 9.76, "author" = John Doe, "updated_at" = 2020-04-30 10:22:28 where "id" is null)"
In this method it uses id column that I don't want, and even I don't know why it used instead using the timestamp.
EDIT 2 on reply of #Uzair Riaz
Unforchantly the problem is still here. After change the controller and model is getting success message, but nothing changes. For example if I want to change value of nivo600 to 1 in recordtime 2020-04-17 00:00:00. After I echo $student in dd:
App\StamboliiskiMeasCanal {#530
#connection: "stamboliiski"
#table: "meas_kanal"
#fillable: array:8 [
0 => "fullname"
1 => "formattedvalue"
2 => "recordtime"
3 => "qualitydesc"
4 => "statedesc"
5 => "author"
6 => "id"
7 => "updated_at"
]
#mapping: array:2 [
"nivo600" => "formattedvalue"
"razhod600" => "formattedvalue"
]
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:6 [
"recordtime" => "2020-04-17 00:00:00"
"nivo600" => "1.86"
"razhod600" => "9.76"
"author" => "Христиан Йорданов"
"formattedvalue" => "9.76"
"updated_at" => "2020-05-05 06:47:26"
]
#original: array:6 [
"recordtime" => "2020-04-17 00:00:00"
"nivo600" => "1.86"
"razhod600" => "9.76"
"author" => "Христиан Йорданов"
"formattedvalue" => "9.76"
"updated_at" => "2020-05-05 06:47:26"
]
#changes: array:4 [
"recordtime" => "2020-04-17 00:00:00"
"author" => "Христиан Йорданов"
"formattedvalue" => "9.76"
"updated_at" => "2020-05-05 06:47:26"
]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
}
It seems that no update is maded...
If those are the only two aliases you are going to use, I suggest overriding the ->fill() method in your model. Map your aliases to the $fillable like so:
class Stamboliiski extends Model
{
protected $fillable = ['fullname', 'formattedvalue', 'recordtime', 'qualitydesc', 'statedesc', 'author', 'id'];
protected $mapping = [
'nivo600' => 'formattedvalue',
'razhod600' => 'formattedvalue'
];
public function fill(array $attributes)
{
foreach ($attributes as $key => $value) {
if (isset($this->mapping[$key])) {
$attributes[$this->mapping[$key]] = $value;
unset($attributes[$key]);
}
}
return parent::fill($attributes);
}
}
Then you can update like so:
$student->update([
'recordtime' => $request->get('recordtime'),
'nivo600' => $request->get('formattedvalueN'),
'razhod600' => $request->get('formattedvalueR'),
'author' => Auth::user()->name
]);

Laravel 5.6 Unit Test maintain login session from beginning until end

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'

Resources