laravel 5.2 retrieve multiple records - laravel-5

i need help here in laravel i'm trying to get two records from the database and pass in these two objects so far the record is retreived but only one variable in passed to the views why is that?
$slides = \App\slides::all();
$followup = Text_Pages::where('machine_name', 'Follow up')->firstOrFail();
$branches = Text_Pages::where('machine_name', 'branches')->firstOrFail();
return view('index',
['slides' => $slides],
['branches' => $branches],
['followup' => $followup]
);

use it like this
return view('index', ['slides' => $slides, 'branches' => $branches, 'followup' => $followup]);

The view method expects all of the view's variables as its second parameter.
return view('index', [
'slides' => $slides,
'branches' => $branches,
'followup' => $followup,
]);
Alternatively, you can use compact to create the array with a bit less typing:
return view('index', compact('slides', 'branches', 'followup'));

Related

Laravel Validating An Array in Update Method unique filter

I am new to Laravel. I try to validate an array in Laravel 9.
for using a unique filter I have a problem.
at first, I try to use this way
$rules = [
'*.id' => 'integer|required',
'*.key' => 'string|unique.settings|max:255|required',
'*.value' => 'array|nullable|max:255',
];
For the Create method, this works, but for updating, the logic is wrong. I need to ignore the current field.
for the update, I try to use this way
private function update(): array
{
foreach ($this->request->all() as $keys => $values) {
// dd($values['id']);
$rules[$keys .'.id' ] = 'integer|required';
$rules[$keys .'.key'] = ['string|max:255|required', Rule::unique('settings', 'key')->ignore($values['id'])];
$rules[$keys .'.value'] = 'array|nullable|max:255';
}
// dd($rules);
return $rules;
}
I got this error
BadMethodCallException: Method Illuminate\Validation\Validator::validateString|max does not exist. in file /Users/mortezashabani/code/accounting/vendor/laravel/framework/src/Illuminate/Validation/Validator.php on line 1534
how can I validate an array in the update method in Laravel 9?
PS: without Rule::unique('settings','key')->ignore($values['id'])] all filter is works without any problem
hello you can try this code in your function
$validated = $request->validate([
'id' => 'required',
'key' => 'string|unique.settings|max:255|required',
'value' => 'array|nullable|max:255',
]);

Missing required parameters for [Route: reviews.show] (from controller)

i want to route a new page from controller, i am getting data successfully when passing in route but getting error.
here is my particular part of controller -
$use = User::find($user->id);
$pos = posts::find($post->id);
//dd($user1, $post1);
return redirect()->route('reviews.show', $pos, $use);
in web.php part -
Route::get('p/{posts}/review/{user}','ReviewController#show')->name('reviews.show');
in show method -
public function show($posts, $user)
{
return view('posts.reviews.reviewshow', ['posts' => $posts], ['user' => $user]);
}
You have to use like this
return redirect()->route('reviews.show', ['posts' => $pos, 'user' => $use]);
route() calls in general take URL parameters as associative array. You are using helper function for it, but it still applies.
redirect()->route('reviews.show', ['posts' => $pos, 'user' => $use]);
When you pass 2 paramters to a route you send them as Array
return redirect()->route('reviews.show', [ $pos, $use ]);
This is your issue

Laravel 5.6. How to test JSON/JSONb columns

$this->assertDatabaseHas() not working with JSON/JSONb columns.
So how can I tests these types of columns in Laravel?
Currently, I have a store action. How can I perform an assertion, that a specific column with pre-defined values was saved.
Something like
['options->language', 'en']
is NOT an option, cause I have an extensive JSON with meta stuff.
How can I check the JSON in DB at once?
UPD
Now can be done like that.
I have solved it with this one-liner (adjust it to your models/fields)
$this->assertEquals($store->settings, Store::find($store->id)->settings);
Laravel 7+
Not sure how far back this solution works.
I found out the solution. Ignore some of the data label, Everything is accessible, i was just play around with my tests to figure it out.
/**
* #test
*/
public function canUpdate()
{
$authUser = UserFactory::createDefault();
$this->actingAs($authUser);
$generator = GeneratorFactory::createDefault();
$request = [
'json_field_one' => [
'array-data',
['more-data' => 'cool'],
'data' => 'some-data',
'collection' => [
['key' => 'value'],
'data' => 'some-more-data'
],
],
'json_field_two' => [],
];
$response = $this->putJson("/api/generators/{$generator->id}", $request);
$response->assertOk();
$this->assertDatabaseHas('generators', [
'id' => $generator->id,
'generator_set_id' => $generator->generatorSet->id,
// Testing for json requires arrows for accessing the data
// For Collection data, you should use numbers to access the indexes
// Note: Mysql dose not guarantee array order if i recall. Dont quote me on that but i'm pretty sure i read that somewhere. But for testing this works
'json_field_one->0' => 'array-data',
'json_field_one->1->more-data' => 'cool',
// to access properties just arrow over to the property name
'json_field_one->data' => 'some-data',
'json_field_one->collection->data' => 'some-more-data',
// Nested Collection
'json_field_one->collection->0->key' => 'value',
// Janky way to test for empty array
// Not really testing for empty
// only that the 0 index is not set
'json_field_two->0' => null,
]);
}
Note: The below solution is tested on Laravel Version: 9.x and Postgres version: 12.x
and the solution might not work on lower version of laravel
There would be two condition to assert json column into database.
1. Object
Consider Object is in json column in database as shown below:
"properties" => "{"attributes":{"id":1}}"
It can assert as
$this->assertDatabaseHas("table_name",[
"properties->attributes->id"=>1
]);
2. Array
Consider array is in json column as shown below:
"properties" => "[{"id":1},{"id":2}]"
It can assert as
$this->assertDatabaseHas("table_name",[
"properties->0->id"=>1,
"properties->1->id"=>2,
]);
Using json_encode on the value worked for me:
$this->assertDatabaseHas('users', [
'name' => 'Gaurav',
'attributes' => json_encode([
'gender' => 'Male',
'nationality' => 'Indian',
]),
]);

Using returned data from controller in Laravel blade

With Laravel, I'm returning data from controller to blade. How to access to datesValid value in blade directly? I want to print the value in that case true.
Controller code:
if (empty($source)) {
return ["recordsTotal" => 0, "recordsFiltered" => 0, 'data' => [], 'datesValid' => $datesValid];
} else {
return ["recordsTotal" => $source['count'][0]['count'], "recordsFiltered" => $source['count'][0]['count'], 'data' => $source['result'], 'datesValid' => $datesValid ];
}
please take a look on this: laravel blade
if from controller you are sending it like this:
return view('x', ['result' => $result]);
and result is an object containing these data.
So you can do:
{{$result->datesValid}}
if it is an array so you can do:
{{$result['datesValid']}}

Is it possible to return multiple variables/arrays in Codeigniter?

Let's say in my model, I have a function that queries two separate tables. I need to pass the results back to my controller to display in my view.
I'm using MongoDB but it should be the same for any other DB. Normally this would work.
$files = $grid->find(array("username" => $profile_id,
"thumbnail" => array('$ne' => true)) );
$return files;
But, I need to go a step further and check to see if the user has a default photo selected.
$getCount = $grid->count(array("username" => $profile_id,
"default" => array('$ne' => true)) );
If I recall correctly, I would normally do ...
$return array($files, $getCount);
Doesn't work though.
Figured it out ... in my function, I did the following.
$files['data'] = $grid->find(array("username" => $profile_id,
"thumbnail" => array('$ne' => true)) );
$files['count'] = $grid->count(array("username" => $profile_id,
"default" => array('$ne' => true)) );
$return files;
In my view, I would manipulate my data accordingly.
echo $files['count'];
foreach( $files['data'] as $obj) {
...
}
To do it the way you wanted to in your original post it'd be something like:
$return array('files' => $files, 'getCount' => $getCount);
I'd split it into two separate model functions. I think its cleaner than fetching and returning the two separate pieces of data from the one function.

Resources