I want to shuffel an array. But it will not work. This is my Query in Laravel
$spielerArray = Spieler::join('PlanungSpieler', 'PlanungSpieler.Player_ID', '=', 'Spieler.Player_ID')
->select('Spieler.Player_ID')->get();
And in the next step I want only shuffle the column Spieler.Player.
$finalShuffleResult = shuffle($spielerArray->Player_ID)
I get Player_ID Instance does not exist on this collection
Here is a part of my collection
Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => App\Spieler Object
(
[table:protected] => Spieler
[connection:protected] => mysql
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[withCount:protected] => Array
(
)
[perPage:protected] => 15
[exists] => 1
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
[Player_ID] => 101
)
How can I get Player_ID with the goal to shuffle them?
use this
$finalShuffleResult = $spielerArray->pluck('Player_ID')->shuffle()->all();
Related
When using laravel built in laravel model methods returns a list of result array. But when querying the same table getting different object. Please check the below code - how can I get the same result set?
$users = User::all();
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[id] => 10
[email] => amirtha#gmail.com
)
[1] => stdClass Object
(
[id] => 12
[email] => renjith#123.com
)
)
But when using the sql query like the below:
$result = DB::table('users as u')
->select('u.id','u.email','u.role','u.created_at')
->join('roles as r','r.id','=','u.role')
->where('u.role', '!=', 1 )
->orderBy('u.name','asc')
->get();
print_r($result);
I get:
Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => App\User Object
(
[fillable:protected] => Array
(
[0] => name
[1] => email
[2] => password
[3] => lastname
[4] => mobile
[5] => role
)
[hidden:protected] => Array
(
[0] => password
[1] => remember_token
)
[casts:protected] => Array
(
[email_verified_at] => datetime
)
[connection:protected] => mysql
[table:protected] => users
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[withCount:protected] => Array
(
)
[perPage:protected] => 15
[exists] => 1
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
[id] => 1
[name] => amritha
[email] => amritha#gmail.com
)
I think your problem is when you want to use the table alias so what about this:
$result = User::query()->from('User as u')
->select('u.id','u.email','u.role','u.created_at')
->join('roles as r','r.id','=','u.role')
->where('u.role', '!=', 1 )
->orderBy('u.name','asc')
->get();
.
This query is the same with "SELECT * FROM USERS"
$users = User::all();
While this one is different from the earlier query
$result = DB::table('users as u')
->select('u.id','u.email','u.role','u.created_at')
->join('roles as r','r.id','=','u.role')
->where('u.role', '!=', 1 )
->orderBy('u.name','asc')
->get();
print_r($result);
I have an application in Laravel that is taking a chunk of data from the dB and rendering it as JSON. The following line of code is generating the title error:
$decodedData['detail']['is_stem'] = isset($detailData->is_stem) ? $detailData->is_stem : 0;
The error is: Cannot use assign-op operators with string offsets
$decodedData is a larger array that is eventually returned as JSON. It is created thusly:
$decodedData = json_decode($detailData->detail, true);
$detailData is an object that looks like this:
App\CareersDetails Object
(
[connection:protected] => mysql
[table:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[withCount:protected] => Array
(
)
[perPage:protected] => 15
[exists] => 1
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
[id] => 4
[code] => 1234
[title] => StackOverFlow
[category] => My Category
[detail] => "Some details in JSON"
[is_stem] => 1
[created_at] => 2018-12-28 17:05:15
[updated_at] => 2018-12-28 17:05:15
)
[original:protected] => Array
(
[id] => 7
[code] => 7890
[title] => StackOverFlowRocks
[category] => My Category
[detail] => "Some details in JSON format"
[is_stem] => 1
[created_at] => 2018-12-28 17:05:15
[updated_at] => 2018-12-28 17:05:15
)
[changes:protected] => Array
(
)
[casts:protected] => Array
(
)
[dates:protected] => Array
(
)
[dateFormat:protected] =>
[appends:protected] => Array
(
)
[dispatchesEvents:protected] => Array
(
)
[observables:protected] => Array
(
)
[relations:protected] => Array
(
)
[touches:protected] => Array
(
)
[timestamps] => 1
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
)
When I debug using:
print_r($detailData->is_stem);
The system outputs a 1. Hence it is set.
Alternatively, is my $decodedData array at fault?
Update
Thanks to the comments, I noticed my $decodedData is not an array, it is a string.
Hence I dumped
`$detailData->detail`
To my browser page with print_r and ran it via a simple, seperate PHP script:
$payload = "JSON FROM $detailData->detail";
$data = json_decode($payload,true);
$data['detail']['is_stem'] = 1;
print_r($data );
This works. Hence my question is now why does the string dump from print_r work and my Laravel based-app doesn't?
Or, in other words, why is json_decode returning a string in the Laravel App but an Array in the PHP app with the same input?
The issue in my instance was my JSON data was double encoded. The fix was:
$decodedData = json_decode(json_decode($detailData->detail), true);
Note, this is not best practice and is a complete oversight on our part so we will be changing this ASAP.
I tried to use "array_merge($a,$b)" but this does not work for what I'm doing. Here are two arrays :
$a =
Array
(
[Mike] => Array
(
[100] => Array
(
[quantity] => 1
[attribute] => 1
)
[200] => Array
(
[quantity] => 1
[attribute] => 1
)
[300] => Array
(
[quantity] => 1
[attribute] => 1
)
[400] => Array
(
[quantity] => 1
[attribute] => 1
)
)
)
$b =
Array
(
[Mike] => Array
(
[500] => Array
(
[quantity] => 1
[attribute] => 1
)
[600] => Array
(
[quantity] => 1
[attribute] => 1
)
)
)
The concept is a user "Mike" adds items to their list (100,200,300,400). This list is saved in the database. Mike logs out and starts a new list a few days later as a anonymous guest, adding items (500,600) saved in his session. When he is finished and logs back in, I want to combine the two lists and save the updated list. If I use "array_merge" and since the array key is [Mike], by design it completely replaces $a with $b rather than merging the item numbers together.
How can I combine this? Also if two items are the same in both lists, such as (100,200,300,400) in one list and (100,500) in the second list (item number "100" being the duplicate here). I would like the [quantity] and [attribute] fields of the "100" in the second list to overwrite the those fields for item "100" in the first list.
Thanks
Kind regards
Use array_replace_recursive function("to update duplicates"):
$result = array_replace_recursive($a, $b);
print_r($result);
The output:
Array
(
[Mike] => Array
(
[100] => Array
(
[quantity] => 1
[attribute] => 1
)
[200] => Array
(
[quantity] => 1
[attribute] => 1
)
[300] => Array
(
[quantity] => 1
[attribute] => 1
)
[400] => Array
(
[quantity] => 1
[attribute] => 1
)
[500] => Array
(
[quantity] => 1
[attribute] => 1
)
[600] => Array
(
[quantity] => 1
[attribute] => 1
)
)
)
http://php.net/manual/en/function.array-replace-recursive.php
You can use the below code. Just be sure to put your latest result first. It will give you the result you want.
$c = $b['Mike']+$a['Mike'];
thanks
I encountered an issue where my Laravel's Eloquent Model does not give me the value of the column called 'id' it just turn to be an integer (0) instead of a string. I though the column was somehow protected but in other Models where the 'id' is an intenger it return the value just fine.
Question: Can't I use VARCHAR for primary keys?
Note: I have to create more tables with respective models where the primary key need to be a string; I'm kinda new Laravel
Migration:
Schema::create('country', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->string('id', 5);
$table->string('name', 45);
$table->string('currency_symbol', 5);
$table->string('currency_name', 45);
$table->float('tax_rate');
$table->string('url')->nullable();
$table->string('support_email', 90);
$table->string('noreply_email', 90);
$table->boolean('active');
$table->boolean('root');
$table->primary('id');
});
Model is really simple:
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
protected $table = 'country';
}
But when i try to retrieve it...
echo Country::find('ve')->first()->toJSON();
//Output:
{"id":0,"name":"Test","currency_symbol":"T".....
// And...
var_dump(Country::find('ve')->first()->id);
//Output:
int:0
But if I use print_r() function this is the output:
App\Http\Models\Country\Country Object
(
[table:protected] => country
[connection:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[id] => ve
[name] => Test
[currency_symbol] => T
[currency_name] => Test currency
[tax_rate] => 12
[url] =>
[support_email] => support#example.com
[noreply_email] => roreply#example.com
[active] => 1
[root] => 1
)
[original:protected] => Array
(
[id] => ve
[name] => Test
[currency_symbol] => T
[currency_name] => Test currency
[tax_rate] => 12
[url] =>
[support_email] => support#example.com
[noreply_email] => roreply#example.com
[active] => 1
[root] => 1
)
[relations:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[dates:protected] => Array
(
)
[dateFormat:protected] =>
[casts:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
[wasRecentlyCreated] =>
)
if necessary:
Laravel version: 5.2
PHP: 5.6.15
If your primary key is not an auto-incrementing value, then you need to let the model know that it's not. Otherwise, it automatically tries to convert the primary key into an integer.
So, try adding this to your model, and then retrieving the value.
public $incrementing = false;
Another thing to note is that you don't need to call first() when you use the find() method. Behind the scenes, it already does that for you so you can shorten it to this:
Country::find('ve')->id;
I am trying to access a collection and create a new object using part of the results.
I keep getting this Undefined offset: 0 and I can't seem to get around it.
Here is my foreach loop in my controller;
foreach($payments as $payment_key => $payment_value) {
//payment_value['Vendor ZIP'] will be something like "SW1A1AA"
$partial_vendor_zip = trim_and_convert($payment_value['Vendor ZIP'], 0, -3);
//$partial_vendor_zip will be something like "SW1A"
//SQL is something like SELECT * FROM postcode_coord WHERE postcode = 'SW1A' LIMIT 1;
$postcode_coord = PostcodeCoord::where('postcode', '=', $partial_vendor_zip)->take(1)->get();
print $postcode_coord['0']->lat; //causes error; Undefined offset: 0
$markers[] = (object)[
"postcode" => $postcode_coord->postcode,
"payment_name" => $payment_value['Contract Title'],
"full_postcode" => $payment_value['Vendor ZIP'],
"lat" => $postcode_coord->lat,
"lng" => $postcode_coord->lng,
];
}
Interestingly, I can still get a print of all the "lat"s - but I also get the error. If I replace that with just a print_r($postcode_coord); then here is a sample of my collection;
Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => App\Models\PostcodeCoord Object
(
[connection:protected] =>
[table:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[id] => 429
[postcode] => CF11
[lat] => 51.47
[lng] => -3.20
[created_at] => 2015-02-20 13:07:01
[updated_at] => 2015-02-20 13:07:01
)
[original:protected] => Array
(
[id] => 429
[postcode] => CF11
[lat] => 51.47
[lng] => -3.20
[created_at] => 2015-02-20 13:07:01
[updated_at] => 2015-02-20 13:07:01
)
[relations:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[dates:protected] => Array
(
)
[casts:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
)
)
)
So that works! But I can't reference the attributes. Even when I try and change my query to something like;
$postcode_coord = PostcodeCoord::where('postcode', '=', $partial_vendor_zip)->take(1)->toArray();
And that just gives me an undefined method error.
Laravel is very confusing to me...
You need to do it like this:
$postcode_coord = PostcodeCoord::where('postcode', '=', $partial_vendor_zip)->first();
print $postcode_coord->lat;
$markers[] = (object)[
"postcode" => $postcode_coord->postcode,
"payment_name" => $payment_value['Contract Title'],
"full_postcode" => $payment_value['Vendor ZIP'],
"lat" => $postcode_coord->lat,
"lng" => $postcode_coord->lng,
];
Note the use of first() instead of take(1)->get(), since the latter will return a collection and the former will return a single item.
If you really want to use take(1)->get(), then you have to do it like this:
$postcode_coord = PostcodeCoord::where('postcode', '=', $partial_vendor_zip)->take(1)->get();
print $postcode_coord[0]->lat;
$markers[] = (object)[
"postcode" => $postcode_coord[0]->postcode,
"payment_name" => $payment_value['Contract Title'],
"full_postcode" => $payment_value['Vendor ZIP'],
"lat" => $postcode_coord[0]->lat,
"lng" => $postcode_coord[0]->lng,
];
Note here the use of 0 instead of '0' and that this index is also used in subsequent references to $postcode_coord.