phpunit test in laravel doesn't show the real sesion table - php

When I use the browser, I see that the values in the session are correct because I use them to display data.
However, when I display a session table in phpunit, it only shows the value for one key:
Controller:
public function add(Book $book)
{
$cart = session('cart');
Book::addToCart($cart, $book);
return back();
}
Model:
public static function addToCart($cart, Book $book)
{
if (!$cart) {
self::createCart($book);
} else {
self::updateCart($cart, $book);
}
}
private static function createCart(Book $book)
{
$cart = [
$book->id => [
'id' => $book->id,
'title' => $book->title,
'quantity' => 1,
'image' => $book->image,
'price' => $book->price
]
];
session(['cart' => $cart]);
}
private static function updateCart($cart, Book $book)
{
if(isset($cart[$book->id])){
$cart[$book->id]['quantity']++;
session(['cart' => $cart]);
} else {
$cart[$book->id] = [
'id' => $book->id,
'title' => $book->title,
'quantity' => 1,
'image' => $book->image,
'price' => $book->price
];
session(['cart' => $cart]);
}
}
for example simple test (result in img)
use WithoutMiddleware;
/** #test */
public function cart_is_created()
{
$book = Book::first();
$this->get('/add-to-cart/' . $book)
->assertSessionHas('cart');
dd(session()->all());
}

Could you show us your tests? When using phpunit with Laravel there's some traits/classes that make sure you connect to a test database instead. This database is usually emptied before testing, which might explain you findings.

Related

Undefined array key "id" in CodeIgniter 4

Undefined array key "id" in CodeIgniter 4
enter image description here
public function update($id)
{
$slug = url_title($this->request->getVar('nama_rak'), '-', true);
$this->rakModel->save([
'id' => $id,
'nama_rak' => $this->request->getVar('nama_rak'),
'slug' => $slug,
'detail_rak' => $this->request->getVar('detail_rak'),
'created_at' => $this->request->getVar('created_at'),
'updated_at' => $this->request->getVar('updated_at')
]);
return redirect()->to('/master/master_rak')->with('pesan', 'Data Berhasil diubah!');
}
this is the construct
class Master extends BaseController
{
protected $rakModel;
public function __construct()
{
$this->rakModel = new RakModel();
}
// Pengadaan Buku
public function master_rak()
{
$data = [
'pages' => 'Master Data',
'title' => 'Data Rak',
'rak' => $this->rakModel->getRak()
];
echo view("master/master_rak", $data);
}

Laravel 9 - Seeder | TypeError array_merge(): Argument #2 must be of type array, int given

I have two tables named Order and OrderItem. While creating data in the Order table, I am trying to enter data into the OrderItem table at the same time. The codes are as follows;
OrderSeeder.php
public function run()
{
Order::factory()->count(30)->create()
->each(function (Order $order) {
Order::factory( OrderItem::class, random_int(1, 5))->create([
'order_id' => $order->id,
]);
});
}
OrderFactory.php
public function definition()
{
return [
'first_name' => $this->faker->name(),
'last_name' => $this->faker->lastName(),
'email' => $this->faker->email(),
];
}
OrderItemFactory.php
public function definition()
{
return [
'product_title' => $this->faker->text(30),
'price' => $this->faker->numberBetween(10.100),
'quantity' => $this->faker->numberBetween(1, 5),
];
}
When I updated the page like this, the problem was solved.
OrderSeeder.php
public function run()
{
Order::factory(10)
->create()
->each(function ($order) {
OrderItem::factory(random_int(1,3))
->create([
'order_id' => $order->id,
]);
});
}
You can use it as a resource when you encounter a similar error..

I have a problem on API Resources Laravel (Maximum stack depth exceeded)

i have a problem when i use API Resources inside another API Resources class like this:
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
but when I remove the class the problem disappears like this :
if (! Route::is('job.*')) {
$data['sites']= $this->sites;
$data['jobs'] = $this->jobs;
}
this is -> image for error
this is my code :
class CustomerResource extends JsonResource
{
public function toArray($request)
{
$data = [
'id' => $this->id,
'name' => $this->name,
'billing_details' => $this->billing_details,
'billing_info' => [
'address' => $this->billing->address,
'street_num' =>$this->billing->street_num,
'country' =>$this->billing->country->name,
'city' =>$this->billing->city,
'postal_code' =>$this->billing->postal_code,
'credit_limit' =>$this->billing->credit_limit,
'payment_term_id' =>$this->billing->payment_term_id,
'send_statement' =>$this->billing->send_statement
],
'contacts' => $this->contacts,
'sitecontact' => $this->sitecontact,
];
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
return $data;
}
}
I called CustomerRessource class on JobRessource class which leads to an infinite loop between them
JobRessource class
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
I fixed it by using this condition on JobRessource
if (Route::is('job.*')) {
$data['customer' ] = new CustomerResource($this->customer);
}
JobRessource with condition
#N69S thank you for your comment

Create new record using 2amigos SelectizeDropDownList in Yii2

I am trying to implement the 2amigos SelectizeDropDownList widget in a form to add new values to a table directly within the dropdown.
I am using the model Book and the Model Author so basically want to be able to add a new author in the book form.
This is the book controller at the update function:
public function actionUpdate($id) {
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
'categories' => BookCategory::find()->active()->all(),
'publishers' => Publisher::find()->all(),
'copirights' => Copiright::find()->all(),
'authors' => Author::find()->all(),
]);
}
}
This is the form:
<?=
$form->field($model, 'author_id')->widget(SelectizeDropDownList::className(), [
// calls an action that returns a JSON object with matched
// tags
'loadUrl' => ['author/list'],
'value' => $authors,
'items' => \yii\helpers\ArrayHelper::map(\common\models\author::find()->orderBy('name')->asArray()->all(), 'id', 'name'),
'options' => [
'class' => 'form-control',
'id' => 'id'
],
'clientOptions' => [
'valueField' => 'id',
'labelField' => 'name',
'searchField' => ['name'],
'autosearch' => ['on'],
'create' => true,
'maxItems' => 1,
],
])
?>
And this is the function author controller:
public function actionList($query) {
$models = Author::findAllByName($query);
$items = [];
foreach ($models as $model) {
$items[] = ['id' => $model->id, 'name' => $model->name];
}
Yii::$app->response->format = \Yii::$app->response->format = 'json';
return $items;
}
The form works fine to load, filter, search and add new items.
But it is not inserting the new typed attribute in the author table.
Do I need to add something in the book controller?
How can I check if it is a new value or a change of an existing author?
Thanks a lot
I made it work with the following code, not sure the most elegant because i am checking the if the author_id is a number or a string.
In my case the author won't be a number anyway.
public function actionUpdate($id) {
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$x = Yii::$app->request->post('Book');
$new_author = $x['author_id'];
if (!is_numeric($new_author)) {
$author = new Author();
$author->name = $new_author;
$author->save();
$model->author_id = $author->id;
}
if ($model->save()) {
return $this->redirect(['index']);
}
} else {
return $this->render('update', [
'model' => $model,
'categories' => BookCategory::find()->active()->all(),
'publishers' => Publisher::find()->all(),
'copirights' => Copiright::find()->all(),
'authors' => Author::find()->all(),
]);
}
}

Symfony method return null

There is a method that takes data from the base value, and outputs it.
If you go through some issues app.php - give NULL, and when entering through app_dev.php - gives the correct boolen value.
P.S function name: isBlocked()
public function indexAction($slug)
{
$product = $this->get('manager.shop.product')->getBySlug($slug);
if (!$product) {
throw $this->createNotFoundException();
}
$this
->get('util.breadcrumbs')
->add('Catalog', $this->generateUrl('categoryIndex'))
->add(
$product->getShop()->getName(),
$this->generateUrl('shopIndex', ['slug' => $product->getShop()->getSlug()])
)->add(
$product->getName(),
$this->generateUrl('productIndex', ['slug' => $product->getSlug()])
);
$this->get('manager.shop.product')->hit($product, $this->getRequest());
foreach ($product->getImages() as $image) {
$this->get('service.image')
->create($image)
->thumbnailize('525x500-800');
}
$shop = $this->get('manager.shop')->getBySlug($product->getShop()->getSlug());
print_r(var_dump($shop->isBlocked()));
return $this->render('MashApplicationBundle:Product:index.html.twig', [
'anotherProducts' => $product->getAnotherShopProducts()->slice(0, 3),
'product' => $product,
'shop' => $shop,
// 'isBlocked' => $shop->isBlocked(),
'addToCartForm' => $this->createForm('checkout', null, ['data' => ['products' => [$product->getId()]]])->createView()
]);
}
Solve:
service memcached restart
in SSH

Categories