Laravel Model Parsing Array - laravel

I have an object in my database that I am trying to retrieve in the Model and parse through to display the text in the blade template. I am not quite sure how to get this to parse correctly. Thank you.
public function getStep1()
{
$step1 = $this->details()->get();
foreach($step1 as $step1)
{
$step1 = $step1->step_1;
return $step1;
}
}
This gets me the following output that I don't know how to parse through. I have tried $step1[0], but that just gives me a [ nothing else.
[["$50,000-$100,000","More than $100,000"]]
My Blade template is simply this...
{{ $question->getStep1() }}
Thank you for your help.
Update:
When I do a var_dump, it says that my "steps" are stored as strings. Is that what's causing a problem? I still can't get within the [].
array (size=9)
'id' => int 1
'question_id' => int 55
'step_1' => string '[["$50,000-$100,000","More than $100,000"]]' (length=43)
'step_2' => string '[["Step2-option1","Step2-option2","Step2-option3"]]' (length=51)
'step_3' => string '[["Step3-option2"]]' (length=19)
'step_4' => null
'step_5' => null
'created_at' => string '2018-10-03 12:29:05' (length=19)
'updated_at' => string '2018-10-03 12:29:05' (length=19)

Instead of returning double array you can just append results to a temporary array and then return that array, check the example code:
public function getStep1()
{
$tempArr = [];
$steps = $this->details()->get();
foreach($steps as $step1)
{
$tempArr[] = $step1->step_1;
}
return $tempArr;
}
Your template code should now iterate over an array we have built right now, so a foreach is required. Like below:
#foreach($question->getStep1() as $step)
// do something with $step
#endforeach

public function getStep1()
{
$steps = $this->details()->get();
$totalSteps = collect();
foreach($steps as $step1)
{
foreach ($step1 as $step)
{
$toalSteps->push($step);
}
}
return $totalSteps;
}

Related

Laravel 9 and Livewire 2 multiple storeAs methods throwing "Call to a member function storeAs() on null" error

I have 6 distinct images that a user needs to upload, so I have 6 different storeAs methods. When I have just one, everything works without fault, but 2 or more, I get a Call to a member function storeAs() on null error. Honesty, my code looks repetitive and dirty, so I'm not surprised.
public function createTentry($id)
{
$trial = Trial::find($id);
$image_plant_general = $this->image_plant_general->storeAs('/', $this->trial->id.'_'.$this->id.'_'.now()->timestamp.'.'.$this->image_plant_general->getClientOriginalExtension(), 'trial-entry-photos');
$image_plant_closeup = $this->image_plant_closeup->storeAs('/', $this->trial->id.'_'.$this->id.'_'.now()->timestamp.'.'.$this->image_plant_closeup->getClientOriginalExtension(), 'trial-entry-photos');
$image_fruit_in_plant = $this->image_fruit_in_plant->storeAs('/', $this->trial->id.'_'.$this->id.'_'.now()->timestamp.'.'.$this->image_fruit_in_plant->getClientOriginalExtension(), 'trial-entry-photos');
$image_fruit_in_plant_closeup = $this->image_fruit_in_plant_closeup->storeAs('/', $this->trial->id.'_'.$this->id.'_'.now()->timestamp.'.'.$this->image_fruit_in_plant_closeup->getClientOriginalExtension(), 'trial-entry-photos');
$image_fruit_in_harvest_single = $this->image_fruit_in_harvest_single->storeAs('/', $this->trial->id.'_'.$this->id.'_'.now()->timestamp.'.'.$this->image_fruit_in_harvest_single->getClientOriginalExtension(), 'trial-entry-photos');
$image_fruit_in_harvest_group = $this->image_fruit_in_harvest_group->storeAs('/', $this->trial->id.'_'.$this->id.'_'.now()->timestamp.'.'.$this->image_fruit_in_harvest_group->getClientOriginalExtension(), 'trial-entry-photos');
Tentry::create([
...
'image_plant_general' => $image_plant_general,
'image_plant_closeup' => $image_plant_closeup,
'image_fruit_in_plant' => $image_fruit_in_plant,
'image_fruit_in_plant_closeup' => $image_fruit_in_plant_closeup,
'image_fruit_in_harvest_single' => $image_fruit_in_harvest_single,
'image_fruit_in_harvest_group' => $image_fruit_in_harvest_group,
]);
return redirect()->route('trial.show', [$trial->evaluation_id, $trial->id]);
}
I would recommend that you use an array and a loop, rather than checking individual properties. Makes for cleaner code, and easier to check the same thing over and over.
Another thing, I added model-route-binding, so that the Trial model is injected as a parameter directly without having to look it up explicitly.
public function createTentry(Trial $trial)
{
$prefix = $this->trial->id.'_'.$this->id.'_'.now()->timestamp.'.';
$images = [
'image_plant_general',
'image_plant_closeup',
'image_fruit_in_plant',
'image_fruit_in_plant_closeup',
'image_fruit_in_harvest_single',
'image_fruit_in_harvest_group'
];
$data = [
// Other Tentry-fields here
];
foreach ($images as $image) {
$data[$image] = $this->{$image}
? $this->{$image}->storeAs('/', $prefix.$this->image_plant_general->getClientOriginalExtension(), 'trial-entry-photos')
: null;
}
Tentry::create($data);
return redirect()->route('trial.show', [$trial->evaluation_id, $trial->id]);
}

Laravel: Trying to push url strings to array in database

I have a field in my AppSetup table called reference_images that is added as follows in the migration: $table->json('reference_images')->nullable(); and casted as an array in the AppSetup model. I have a method that adds image urls to the database. If it's for the reference_image field, I am trying to push it to the array but I keep getting an "Array to String conversion" error in Laravel.
public function addImagesToAppSetup($imageType=null, $image=null)
{
$appSetup = AppSetup::where('store', '=', id())->first();
if ($image) {
if ($imageType == "reference_images") {
$originalArray = $appSetup->$imageType;
$originalArray[] = $image;
$appSetup->$imageType = array_values(array_unique($originalArray));
} else {
$appSetup->$imageType = $image;
}
}
$appSetup->save();
return response()->json(['status' => 1, 'data' => $appSetup]);
}
Since reference_images is of type json, doing array_values(array_unique($originalArray)); is still an Array. You will have to convert it to json.
e.g. using collect()->json() docs
$appSetup->$imageType = collect($originalArray)->unique()->values()->toJson();

another "can't save multiple checkbox" and "must be of the type array, string given"

I have seen many same question about this problem but I can't figure out how to fix mine
so I'm trying to save multiple checkbox and I think this one will work but now I get "must be of the type array, string given".
By the way this is my controller
public function store(Request $request)
{
// $multi = Multi::create($request->only(['data'])->implode(', '));
// $multi = Multi::select('data')->implode();
$multis = implode(',', $request->get('data'));
$multis = Multi::create(['data' => $request->get('data')]);
return redirect()->route('multi.create')->with('success', 'berhasil.');
and this is my create.blade.php
#foreach($multis as $multi)
{{$multi['data']}}<br>
#endforeach
<br>----------------<br>
{{Form::open(['action'=>'MultiController#store'])}}
{{Form::checkbox('data[]','A')}}A<br>
{{Form::checkbox('data[]','B')}}B<br>
{{Form::checkbox('data[]','C')}}C<br>
{{Form::submit('TAMBAH')}}
{{Form::close()}}
Try this
$multis = implode(',', $request->data));
$multis = Multi::create(['data' => $multis]);
You have to add fields name as a key of array and define all the data into different variables like this this will work.
$multis1 = implode(',', $request->d);
$multis2 = implode(',', $request->i);
$multis3 = implode(',', $request->s);
$multis4 = implode(',', $request->c);
$multis= Test::create(array('d' => $multis1,'i' => $multis2,'s' => $multis3,'c' => $multis4));

Laravel 5.4 Return as array not object

The following method is intended to return an array with another array, 'data' and an Object (The result of some eloquent query).
It is however returning an array with two objects in it; $data is somehow being converted to an object with multiple child-objects, rather than being an array of objects. It should be noted that a dd($data) before the return statement reveals that it is indeed an array of objects. I think that somehow the Laravel middleware that handles response is returning this as an object instead...
Any idea how to work around this?
public function getTestData($id) {
$participants = Participant::where('test_id', $id)->with('testRecords')->get();
$finalRecordValue = TestRecord::where('test_id', $id)->orderBy('created_at', 'desc')->first();
$data = [];
foreach ($participants as $participant) {
foreach ($participant->testRecords as $testRecord) {
if (!array_key_exists((int)$testRecord->capture_timestamp, $data)) {
$data[$testRecord->capture_timestamp] = (object)[
'category' => $testRecord->capture_timestamp,
'value' . "_" . $participant->id => $testRecord->score
];
} else {
$data[$testRecord->capture_timestamp]->{"value" . "_" . $participant->id} = $testRecord->score;
}
}
}
return [$data, Auth::user()->tests()->findOrFail($id)];
}
Try this before excuting return sentence or in it:
array_values($data);

how can I catch a single variable in array of Object in CodeIgniter?

I have probabbly a eal probleme with array . I have a request :
in my model
public function getHomme ($limit ,$offset)
{
$this->db->select('id,nom,prix,nom_marques,nom_path,quantite,semelle_interieure,libelle_fermeture,libelle_style,libelle_talon,libelle_doublure,libelle_semelle,libelle_dessus');
$this->db->from('chaussure');
$this->db->join('gnr_convenir', 'gnr_convenir.identifiant_chaussure = chaussure.id');
$this->db->join('images', 'images.id_chaussure = chaussure.id');
$this->db->join('marques', 'marques.idmarques = chaussure.identifiant_marques');
$this->db->join('fermeture', 'fermeture.idfermeture = chaussure.identifiant_fermeture');
$this->db->join('style', 'style.idstyle = chaussure.identifiant_style');
$this->db->join('talon', 'talon.idtalon = chaussure.identifiant_talon');
$this->db->join('doublure', 'doublure.iddoublure = chaussure.identifiant_doublure');
$this->db->join('materiauSemelle', 'materiauSemelle.idmateriauSemelle = chaussure.identifiant_semelle');
$this->db->join('dessus', 'dessus.iddessus = chaussure.identifiant_dessus');
$this->db->where('identifiant_genre', 1);
$this->db->order_by("id", "desc");
$this->db->limit($limit,$offset);
$query = $this->db->get();
$ligne= $query->num_rows();
if($query->num_rows()>0)
{
foreach($query->result()as $row)
{
$data[] = $row;
}
$data['ligne'] = $ligne;
return $data;
}
so here I need 2 things:
one the object on data and the other is $ligne (number of rows )
so it seems like this when I try to make var_dump($data)
array
'rows' =>
array
0 =>
object(stdClass)[21]
public 'id' => string '89' (length=2)
public 'nom' => string 'zoro' (length=4)
public 'prix' => string '12460.00' (length=8)
1 =>
object(stdClass)[22]
public 'id' => string '87' (length=2)
public 'nom' => string 'adizero' (length=7)
public 'prix' => string '124000.00' (length=9)
'ligne' => int 2
but when I try to write:
var_dump($data['ligne']) in my controller
I have an error message
A PHP Error was encountered
Severity: Notice
Message: Undefined index: ligne
Filename: controllers/client.php
Line Number: 143
null
I need those 2 data in my view, so in my view I thought to use $ligne like this:
$numberLigne = $ligne ;
As a test, could you echo ligne in your model to make sure that your join query is working right? I have no way of knowing without seeing your full table.
Also, any reason why you use:
if($query->num_rows()>0)
Instead of
if($ligne > 0):
Being that you just set that variable?

Resources