Laravel: test response is different from real response - laravel

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.

Related

Illuminate\Foundation\Auth\User returning keyType: int

I am using the following trait to generate UUID's for my user model. I have setup a listener to the following event: Illuminate\Auth\Events\Login. This works when you just normally sign-in to the app (using Laravel Breeze). But when I manually do auth()->user($user) I get back an instance of Illuminate\Foundation\Auth\User where the keyType is an integer and incrementing is set to true, although my trait does otherwise.
Anyone knows how to fix this?
<?php
namespace App\Traits;
use Ramsey\Uuid\Uuid;
trait Uuidable
{
/**
* Cast the primary key type as a string
*/
public function initializeUuidable()
{
$this->setKeyType('string');
}
/**
* Set the model to none incrementing
*
* #return bool
*/
public function getIncrementing()
{
return false;
}
/**
* Set the key of the model
*
* #return void
*/
public static function bootUuidable()
{
static::creating(function ($model) {
if (!isset($model->attributes[$model->getKeyName()])) {
$model->incrementing = false;
$uuid = Uuid::uuid4();
$model->attributes[$model->getKeyName()] = $uuid->toString();
}
}, 0);
}
}
Illuminate\Foundation\Auth\User {#1494 ▼
#connection: "mysql"
#table: "users"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:13 [▶
"id" => "31f12e1a-964c-4580-8a20-263c8bb7bf95"
"first_name" => "test"
"last_name" => "user"
"email" => "test#mrpackage.com"
"email_verified_at" => null
"password" => "$2y$10$vTAYxvC4s95PpF5BmzC0p..ZiQfcn3WARxXalgmd1kVZn5X1S/F02"
"last_login_id" => null
"remember_token" => null
"welcome_valid_until" => null
"printer_id" => null
"created_at" => "2021-09-15 14:38:00"
"updated_at" => "2021-09-15 14:38:20"
"deleted_at" => null
]
#original: array:13 [▶
"id" => "31f12e1a-964c-4580-8a20-263c8bb7bf95"
"first_name" => "test"
"last_name" => "user"
"email" => "test#mrpackage.com"
"email_verified_at" => null
"password" => "$2y$10$vTAYxvC4s95PpF5BmzC0p..ZiQfcn3WARxXalgmd1kVZn5X1S/F02"
"last_login_id" => null
"remember_token" => null
"welcome_valid_until" => null
"printer_id" => null
"created_at" => "2021-09-15 14:38:00"
"updated_at" => "2021-09-15 14:38:20"
"deleted_at" => null
]
#changes: array:3 [▶
"password" => "$2y$10$vTAYxvC4s95PpF5BmzC0p..ZiQfcn3WARxXalgmd1kVZn5X1S/F02"
"welcome_valid_until" => null
"updated_at" => "2021-09-15 14:38:20"
]
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶
0 => "*"
]
#rememberTokenName: "remember_token"
}

Laravel Fetch Value form Session

Here is my Session and i would like to fetch the value from Sample_table to get the original array value how can i do that ?
{{ dd(Session::get('sample')[0]) }}
Sample_table{#266 ▼
#fillable: array:6 [▶]
#table: "Sample_table"
#primaryKey: "id"
+timestamps: true
#connection: "mysql"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:20 [▶]
#original: array:20 [▼
"id" => "9"
"firstName" => "test"
"lastName" => "asdf"
"middleName" => "test"
"contactNo" => "2147483647"
"emailAddress" => "test#gmail.com"
"residenceAddress" => "afsf"
"province_id" => "6"
"city_id" => "3"
"barangay_id" => "16982"
"copyMailing" => null
"mailingAddress" => null
"mailing_province_id" => "6"
"mailing_city_id" => "3"
"mailing_barangay_id" => "16982"
"status" => "0"
"userIdentity" => "0"
"global_id" => "0"
"updated_at" => "0000-00-00 00:00:00"
"created_at" => "0000-00-00 00:00:00"
]
You can use ->getRawOriginal():
Session::get('sample')[0]->getRawOriginal();

Laravel model not filling 1 specific column

In my model, i have the following fillable array:
protected $fillable = [
'first_name',
'last_name',
'email',
'street',
'house_number',
'province',
'phone',
'country',
'date_of_birth',
'postcode',
'account_id',
'user_id'
];
user_id is nullable and account_id is not.
When i try to create a new entity, user_id stays null in my database.
This is my code for saving the entity:
#in controller
$this->dispatch(new Job($user = $request->user(), $client = new Client(),
$request->only($client->getFillable())
));
#in job class
$client = $this->client->create(array_merge([
'user_id ' => $this->user->id,
'account_id' => $this->user->account->id
],$this->variables));
This is all of the data going into the create method:
"user_id " => 3
"account_id" => 3
"first_name" => "patrick"
"last_name" => "vd pols"
"email" => "patrickvanderpolssad22dxsxs#live.nl"
"street" => "Dijkgraaf 2"
"house_number" => "asdasd"
"province" => "Drenthe"
"country" => "asdasdsad"
"date_of_birth" => "14-12-2019"
"postcode" => "3155GA"
Both user with ID 3 and account with ID 3 exist in my database.
After saving the entity, the user_id is null:
App\Client {#384 ▼
#fillable: array:12 [▶]
#connection: "mysql"
#table: "clients"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: true
#attributes: array:13 [▼
"account_id" => 3
"first_name" => "patrick"
"last_name" => "vd pols"
"email" => "patrickvanderpolssad22dxsxs#live.nl"
"street" => "Dijkgraaf 2"
"house_number" => "asdasd"
"province" => "Drenthe"
"country" => "asdasdsad"
"date_of_birth" => Carbon\Carbon #1576281600 {#385 ▶}
"postcode" => "3155GA"
"updated_at" => "2019-12-14 00:10:03"
"created_at" => "2019-12-14 00:10:03"
"id" => 8
]
#original: array:13 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
What am i not seeing?
Thanks!
Edit:
I am an idiot.
There was an extra space after user_id:
'user_id ' => $this->user->id
Solved.
You did find the catch!
But since you want me to write the answer, I gladly do it.
You had an extra space on your key 'user_id ' => $this->user->id

Laravel Forms - Fill a Multiple Select Input to View

I have a tricky situation here.
I have an Edit form where I can fill the existing values when I'm editing an index. (I pass a Model Object in the controller). It works for every input field, but I need to fill a certain Multiple Select field which I don't know how to do it. I tried passing this specific value in the object, either as array (which contains the IDs of each selectable value) which crashes the view or as a json string using json_encode. I read an article here where the person accomplish this but it's done with a many-to-many relationship table, but the value I need to fill doesn't come from the table.
Resulting Object using dd()
Contact {#408 ▼
+table: "contacts"
#dates: array:1 [▼
0 => "deleted_at"
]
+fillable: array:5 [▼
0 => "nombre"
1 => "apellido"
2 => "cargo"
3 => "empresa_id"
4 => "groups"
]
#casts: array:5 [▼
"nombre" => "string"
"apellido" => "string"
"cargo" => "string"
"empresa_id" => "integer"
"groups" => "array"
]
#connection: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:9 [▼
"id" => 4
"nombre" => "redacted"
"apellido" => "redacted"
"cargo" => "redacted"
"empresa_id" => 2
"created_at" => "2017-03-09 20:30:19"
"updated_at" => "2017-11-29 17:30:55"
"deleted_at" => null
"groups" => "["2","3","4"]"
]
#original: array:9 [▼
"id" => 4
"nombre" => "redacted"
"apellido" => "redacted"
"cargo" => "redacted"
"empresa_id" => 2
"created_at" => "2017-03-09 20:30:19"
"updated_at" => "2017-11-29 17:30:55"
"deleted_at" => null
"groups" => "["2","3","4"]"
]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▼
0 => "*"
]
#dateFormat: null
#touches: []
#observables: []
#with: []
+exists: true
+wasRecentlyCreated: false
#forceDeleting: false
Multiple Select Form.
{!! Form::label('groups', 'Grupos:') !!} </br>
{!! Form::select('groups', $groups, null, ['data-actions-box' => 'true', 'multiple'=>'multiple']) !!}
If more information is needed I will edit the question.
Fixed it by transforming the array elements to int before passing it to json_encode.

Laravel use controller in the same function?

I am retrieving entities from a database, however I do have pivot table that links users and entities and for each entity I want to retrieve a user, the problem is I don't know how to use a collection inside a laravel controller function:
public function handle()
{
$dir = "public/ical/*";
foreach(glob($dir) as $file)
{
$entity_id = preg_match("/\d/", $file);
$entity = Entity::where('id', $entity_id)
->with('users')
->first();
dd($entity->users->id); //I want to retrieve that.
$icals = new ICal($file, array(
'defaultSpan' => 2,
'defaultTimeZone' => 'UTC',
'defaultWeekStart' => 'MO',
'skipRecurrence' => false,
'useTimeZoneWithRRules' => false,
));
$time_period = array(
'interval' => true,
);
if ($time_period['interval']) {
$events = $icals->eventsFromInterval('2 week');
$count = 1;
}
foreach ($events as $event) {
$dtstart = $icals->iCalDateToDateTime($event->dtstart);
$dtend = $icals->iCalDateToDateTime($event->dtend);
$dtstart_tz = $icals->iCalDateToDateTime($event->dtstart_tz);
$dtend_tz = $icals->iCalDateToDateTime($event->dtend_tz);
$database_event = new Event;
$database_event->type = "External Event";
$database_event->startdate = $dtstart->format('d-m-Y');
$database_event->endate = $dtend->format('d-m-Y');
$database_event->startime = $dtstart_tz->format('H:i');
$database_event->endtime = $dtend_tz->format('H:i');
$database_event->title = $event->summary;
$database_event->description = $event->description ;
$database_event->location = $event->location;
$database_event->entity_id = $entity_id;
$database_event->save();
$this->info("Event Retrieved");
$count++;
}
data dump dd($entity) gives:
App\Entity {#620
#table: "entities"
+timestamps: true
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:16 [
"id" => 1
"name" => "dasd"
"type" => "dsa"
"email" => "adas"
"logo" => null
"twitter_business" => null
"facebook_business" => null
"instagram_business" => null
"google_places" => null
"ical" => null
"slug" => null
"api_key" => null
"geoloc_id" => null
"deleted" => 0
"created_at" => null
"updated_at" => null
]
#original: array:16 [
"id" => 1
"name" => "dasd"
"type" => "dsa"
"email" => "adas"
"logo" => null
"twitter_business" => null
"facebook_business" => null
"instagram_business" => null
"google_places" => null
"ical" => null
"slug" => null
"api_key" => null
"geoloc_id" => null
"deleted" => 0
"created_at" => null
"updated_at" => null
]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: array:1 [
"users" => Illuminate\Database\Eloquent\Collection {#622
#items: array:2 [
0 => App\Entity {#630
#table: "entities"
+timestamps: true
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:16 [
"id" => 1
"name" => "dasd"
"type" => "dsa"
"email" => "adas"
"logo" => null
"twitter_business" => null
"facebook_business" => null
"instagram_business" => null
"google_places" => null
"ical" => null
"slug" => null
"api_key" => null
"geoloc_id" => null
"deleted" => 0
"created_at" => null
"updated_at" => null
]
#original: array:18 [
"id" => 1
"name" => "dasd"
"type" => "dsa"
"email" => "adas"
"logo" => null
"twitter_business" => null
"facebook_business" => null
"instagram_business" => null
"google_places" => null
"ical" => null
"slug" => null
"api_key" => null
"geoloc_id" => null
"deleted" => 0
"created_at" => null
"updated_at" => null
"pivot_user_id" => 1
"pivot_entity_id" => 1
]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: array:1 [
"pivot" => Illuminate\Database\Eloquent\Relations\Pivot {#629
+parent: App\Entity {#597
#table: "entities"
+timestamps: true
#connection: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: []
#touches: []
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [
0 => "*"
]
}
#foreignKey: "user_id"
#relatedKey: "entity_id"
#guarded: []
#connection: null
#table: "entity_user"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:2 [
"user_id" => 1
"entity_id" => 1
]
#original: array:2 [
"user_id" => 1
"entity_id" => 1
]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: []
#touches: []
+timestamps: false
#hidden: []
#visible: []
#fillable: []
}
]
#touches: []
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [
0 => "*"
]
}
1 => App\Entity {#633
#table: "entities"
+timestamps: true
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:16 [
"id" => 2
"name" => "ddasd"
"type" => "fsdf"
"email" => "fsdf"
"logo" => null
"twitter_business" => null
"facebook_business" => null
"instagram_business" => null
"google_places" => null
"ical" => null
"slug" => null
"api_key" => null
"geoloc_id" => null
"deleted" => 0
"created_at" => null
"updated_at" => null
]
#original: array:18 [
"id" => 2
"name" => "ddasd"
"type" => "fsdf"
"email" => "fsdf"
"logo" => null
"twitter_business" => null
"facebook_business" => null
"instagram_business" => null
"google_places" => null
"ical" => null
"slug" => null
"api_key" => null
"geoloc_id" => null
"deleted" => 0
"created_at" => null
"updated_at" => null
"pivot_user_id" => 1
"pivot_entity_id" => 2
]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: array:1 [
"pivot" => Illuminate\Database\Eloquent\Relations\Pivot {#625
+parent: App\Entity {#597}
#foreignKey: "user_id"
#relatedKey: "entity_id"
#guarded: []
#connection: null
#table: "entity_user"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:2 [
"user_id" => 1
"entity_id" => 2
]
#original: array:2 [
"user_id" => 1
"entity_id" => 2
]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: []
#touches: []
+timestamps: false
#hidden: []
#visible: []
#fillable: []
}
]
#touches: []
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [
0 => "*"
]
}
]
}
]
#touches: []
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [
0 => "*"
]
}
Your relationship between the entity object and the user object is a many to many. You cannot do
$entity->users->id
This is because you are trying to the id property on a collection of users.
Try this:
$entity->users->first()->id
To loop through your users, do this:
foreach ($entity->users as $user)
{
echo($user->id);
}

Resources