How to change collection column value in laravel - laravel

I have a laravel collection that's like this:
$loan = Loans::where([
['OL_TEMP_APP_NO', $appNo]
])
->get();
The $loan collection returns principal, terms, code. The code corresponds to a string. Example 1 = new, 2 = processing, 3 = approved.
How do I parse the values under code before sending them to the view?

You can use CASE WHEN to convert the integer to string code:
$loan = Loans::where([
['OL_TEMP_APP_NO', $appNo]
])
->select('principal', 'terms', DB::raw("
(CASE code
WHEN 2 THEN 'processing'
WHEN 3 THEN 'approved'
ELSE 'new' END) AS code
"))
->get();

if you already know the value of code, or code will always have some fixed values, then you can use like following:
public function getAll(){
// ...
$loans = Loans::where([['OL_TEMP_APP_NO', $appNo]])->get();
$data = [];
foreach($loans as $loan){
$code = Code::getValue($loan->code);
$data[] = [
'principal' => $loan->principal,
'terms' => $loan->terms,
'code' => ($loan->code == 1) ? 'new' : ( ($loan->code == 2) ? 'processing' : 'approved')
]
}
return $data;
}

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]);
}

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));

How can i seed with faker a random id or null in Laravel?

I am trying to seed a parent_id column with a random id of the same table or let it be null.
This i thought it will work:
...
'parent_id' => $faker->boolean() ? Page::all()->random()->id : null,
...
But i get the following error:
You requested 1 items, but there are only 0 items available.
Does anyone know how to do this?
Update1:
Using pseudoanime answer i tried the flowing :
$factory->define(Page::class, function (Faker\Generator $faker) {
...
$parent_id = null;
...
$has_parent = $faker->boolean(50);
Log::debug('$has_parent' . $has_parent);
if ($has_parent) {
$parents = Page::all();
Log::debug('$parents' . count($parents));
if ($parents->isEmpty()) {
Log::debug('isEmpty');
$parent_id = null;
} else {
Log::debug('$parents->random()' . print_r($parents->random(), true));
$parent_id = $parents->random()->id;
}
}
return [
...
'parent_id' => $parent_id,
...
];
}
From what i can see every time it is run Page::all(); return empty.
Any idea why that is?
Try this:
'parent_id' => $faker->boolean(50) ? Page::orderByRaw('RAND()')->first()->id : null,
Essentially we're saying, order by random, get the first and then get it's id.
boolean(50) should give you a 50% chance of true, so 50% false.
$factory->define(Page::class, function (Faker\Generator $faker) {
$ids = Page::pluck('id')->toArray();
return [
'parent_id' = empty($ids) ? null : $faker->optional(0.9, null)->randomElement($ids); // 10% chance of null
];
});
Given "Parent" as the parent model, I do this:
first seed the Parent;
seed the Child table using this code in the factory:
'parent_id' => $faker->optional()->randomElement(App\Parent::all()->pluck('id'))
It works because faker's randomElement() takes an array which you populate with all and only the 'id' values of the parent table.
The optional() faker's modifier does or doesn't put a NULL in the parent_id at random. As stated in faker's GitHub, optional() sometimes bypasses the provider to return a default value instead (which defaults to NULL).
You can also specify the probability of receiving the default value and the default value to return.
NB: you can't do anything if the Parent table isn't seeded. If so, consider the answer of dlnsk.
Your error is happening because your query to page (page:all()->random()) returns no results.
Basically your issue is that you care trying to create a parent to a page before a page is even created.
You can should try something like check if the Page::all() returns a non empty collection, if yes, then get a random element from there, if not, create a new element.
I personally would do something like create a class for null parent element & one that would do null & non-empty parent element.
$factory->defineAs(Page::class, 'ParentPage', function (Faker $faker) {
return [
//the rest of your elements here
'parent_id' => null
];
});
$factory->defineAs(Page::class, 'page', function (Faker $faker) {
$has_parent = $faker->boolean();
if($has_parent) {
$parents = Page::all();
if($parents->isEmpty()) {
$parent_id = factory(Page::class, 'ParentPage')->create()->id;
} else {
$parent_id = $parents->random()->id;
}
}
return [
//the rest of your elements here
'parent_id' => $has_parent? $parent_id : null
];
});
You can create regular pages like factory(Page::class, 'page')->times(50)->create(); in your seeder
The code above is not tested, but the logic should be correct.
public function run()
{
factory(\App\Comment::class, 30)->make()->each(function ($comment){
$comments = Comment::all();
if ($comments->count() == 0) {
$comment->parent = null;
} else {
$rand = random_int(1, $comments->count());
if ($rand >= 2 && $rand <= 5){
$comment->parent = null;
}elseif ($rand >= 12 && $rand <=17){
$comment->parent = null;
}elseif ($rand >= 22 && $rand <= 27){
$comment->parent = null;
}else{
$comment->parent = $rand;
}
}
$comment->save();
});
}

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?

Codeigniter $this->db->affected_rows() always returns 1

I'm using codeigniter version 2.0.3. I'm trying get the number of affected rows after an update query using
$this->db->affected_rows
It always returns 1 even if no row had been updated. I tried with
mysql_affected_rows()
and it returns -1 for a query failure and 0 if no record had been updated .
Edit included my code
I'm just using
$country_id = $this->input->post('country_id');
$time=$this->input->post('time');
$insert_array = array(
'country' => $this->input->post('name')
);
$this->db->update('country_master', $insert_array, array("country_id" => $country_id,"last_updated"=>$time));
$afftectedRows=$this->db->affected_rows();
Actually my code was like this
if (!$country_id) {
$this->db->insert('country_master', $insert_array);
$id = $this->db->insert_id();
} else {
$this->db->update('country_master', $insert_array, array("country_id" => $country_id, "last_updated" => $time));
}
$afftectedRows = $this->db->affected_rows();
And i modified it to
if (!$country_id) {
$this->db->insert('country_master', $insert_array);
$id = $this->db->insert_id();
} else {
$this->db->update('country_master', $insert_array, array("country_id" => $country_id, "last_updated" => $time));
$afftectedRows = $this->db->affected_rows();
}
And its working fine now.
And thank you very much for the replies..

Resources