controller store function array laravel 5.5 - arrays

I need some help. I have a problem with store function with array in laravel. When I submit my form, I got error massage that "ksort() expects parameter 1 to be array, string given".
This is my store function :
public function store(request $request) {
$input=$request->all();
$images=array();
$total = count($request->path_scan_ijazah);
// return $total;
if($files=$request->file('path_scan_ijazah')){
for ($i=0; $i < $total; $i++) {
$nip[] = $request->nip;
$instansi[] = $request['nama_instansi_pendidikan'][$i];
$jurusan[] = $request['nama_jurusan'][$i];
$jenjang[] = $request['jenjang_pendidikan'][$i];
$gelar[] = $request['gelar'][$i];
$thn_masuk = $request['tahun_masuk'][$i];
$thn_lulus = $request['tahun_lulus'][$i];
$path = $request['path_scan_ijazah'][$i]->store('public/upload/ijazah');
$images[] = $path;
$data[] = Education::insert([
'nip_employee' => $nip,
'nama_instansi_pendidikan' => $instansi,
'nama_jurusan' => $jurusan,
'jenjang_pendidikan' => $jenjang,
'gelar' => $gelar,
'tahun_masuk' => $thn_masuk,
'tahun_lulus' => $thn_lulus,
'path_scan_ijazah' => $images
]);
}
// dd($data);
}
Please help me, what should I do?

Related

How to pass multi-dimensional arrays through url as query parameters? and access these parameters in laravel 6.0

I am trying to pass a multi-dimensional array as a query parameter in the below URL:
{{serverURL}}/api/v1/classes?with[]=section.courseteacher&addl_slug_params[0][0]=test&addl_slug_params[0][1]=test1&addl_slug_params[0][2]=test0
what is wrong with the above URL?
My code to access these parameters in Laravel 6.0 is below:
$addl_slug_params = $request->query('addl_slug_params');
$i=0;
foreach ($addl_slug_params as $s) {
$j=0;
foreach($s as $asp) {
print_r('addl_slug_params : ('.$i.':'.$j.') : '.$asp); die();
$j=$j+1;
}
$i = $i+1;
}
Result:
addl_slug_params : (0:0) : test
Problem: test1 and test0 are not accessible..
What should I do?
The problem is the die(); after printr(), the loop will run once, aka only addl_slug_params : (0:0) : test
To help you visualize it better, I added an extra break after each loop:
foreach ($addl_slug_params as $s) {
$j=0;
foreach($s as $asp) {
echo('addl_slug_params : ('.$i.':'.$j.') : '.$asp);
echo nl2br(PHP_EOL);
$j=$j+1;
}
$i = $i+1;
}
Will result in the following:
addl_slug_params : (0:0) : test
addl_slug_params : (0:1) : test1
addl_slug_params : (0:2) : test0
here is a solution for multi-dimensional arrays. Developed in 2~ hours, definitely needs improvement but hopefully helps you out :)
Route::get('example', function (\Illuminate\Http\Request $request) {
$addl_slug_params = [
[
1 => [
'title' => 'Test 1',
'slug' => 'test1'
],
2 => [
'title' => 'Test 2',
'slug' => 'test2'
],
3 => [
'title' => 'Test 3',
'slug' => 'test3'
],
],
];
// Encode
$prepend = 'addl_slug_params';
$query = "?$prepend";
$tempSlugs = $addl_slug_params[0];
$lastIndex = count($tempSlugs);
foreach ($addl_slug_params as $pIndex => $params) {
foreach ($params as $sIndex => $slugData) {
$tempQuery = [];
foreach ($slugData as $sdIndex => $data) {
// Replace '-' or ' -' with ''
$encodedString = preg_replace('#[ -]+#', '-', $data);
// title = test1
$tempString = "$sdIndex=$encodedString";
$tempQuery[] = $tempString;
}
$dataQuery = implode(',', $tempQuery);
$appendStr = ($sIndex !== $lastIndex) ? "&$prepend" : '';
// Set the multidimensional structure here
$query .= "[$pIndex][$sIndex]=[$dataQuery]$appendStr";
}
}
// DECODE
// ?addl_slug_params[0][1]=[title=Test-1,slug=test1]&addl_slug_params[0][2]=[title=Test-2,slug=test2]&addl_slug_params[0][3]=[title=Test-3,slug=test3]
$slugParams = $request->query('addl_slug_params');
$slugParamData = [];
foreach ($slugParams as $slugItems) {
foreach ($slugItems as $slugItem) {
// Replace [title=test,slug=test1] into 'title=test,slug=test1' and explode
// into into an array, and split title=test into [title => test]
$splitArray = explode(',', (str_replace(array('[', ']'), '', $slugItem)));
$slugItemData = [];
foreach ($splitArray as $value) {
$data = explode('=', $value);
$slugItemData[$data[0]] = $data[1];
}
$slugParamData[] = $slugItemData;
}
}
dd($slugParamData);
});
I have solved the problem using associative arrays as it gives more flexibility and Garrett's solution definitely helped
new url: {{serverURL}}/api/v1/classes?with[]=section.courseteacher&addl[users][params]=name
laravel code:
`
foreach ($addl_data_array as $addl_slug => $addl_slug_data) {
foreach ($addl_slug_data as $key => $value) {
$params = null;
$where_raw = null;
$where_has = null;
$with_relationships = null;
$with_timestamps = null;
}
}
`

Laravel - Save multiple field values in json/array in a column

I have 3 form fields name, address, profile_photo. I want to save there 3 fields in json/array format in a single column so that I can retrieve it later in view blade.
My form looks like this
I tried
$customer_details= new Customer;
{
$profile_photo = $request->file('profile_photo');
for ($i=0; $i < count(request('profile_photo')); $i++) {
$pro_fileExt = $profile_photo[$i]->getClientOriginalExtension();
$pro_fileNameToStore = time().'.'.$pro_fileExt;
$pro_pathToStore = public_path('images');
Image::make($profile_photo[$i])->save($pro_pathToStore . DIRECTORY_SEPARATOR. $pro_fileNameToStore);
$profile_ph = '/images/'.$pro_fileNameToStore; }
$cust_details=json_encode(request(['name', 'address', $profile_ph]));
$customer_details->details = $cust_details;
$customer_details->save();
}
With this profile_photo is not saved but other data are saved as:
{"name":["john","Sam"],"address":["CA","FL"]}
How can I save all there fields including profile_photo and show each details distinctly later on view blade?
Hope this will help you.
$customer_details = new Customer;
$profile_photo = $request->file('profile_photo');
$profile_ph = [];
for ($i = 0; $i < count(request('profile_photo')); $i++) {
$pro_fileExt = $profile_photo[$i]->getClientOriginalExtension();
$pro_fileNameToStore = time() . '.' . $pro_fileExt;
$pro_pathToStore = public_path('images');
Image::make($profile_photo[$i])->save($pro_pathToStore . DIRECTORY_SEPARATOR . $pro_fileNameToStore);
$profile_ph[$i] = '/images/' . $pro_fileNameToStore;
}
$data = [
'name' => $request->name,
'address' => $request->address,
'profile_ph' => $profile_ph
];
$customer_details->details = json_encode($data);
$customer_details->save();
The details column should be text if you are using mysql.
Try this:
$names = $request->input('name');
$addresses = $request->input('address');
$profile_photos = $request->file('profile_photo');
for ($i = 0; $i < count($names); $i++) {
$customer_details = new Customer;
$pro_fileExt = $profile_photos[$i]->getClientOriginalExtension();
$pro_fileNameToStore = time() . '.' . $pro_fileExt;
$pro_pathToStore = public_path('images');
Image::make($profile_photos[$i])->save($pro_pathToStore . DIRECTORY_SEPARATOR . $pro_fileNameToStore);
$profile_ph = '/images/' . $pro_fileNameToStore;
$cust_details = json_encode([
'name' => $names[$i],
'address' => $addresses[$i],
'profile_photo' => $profile_ph,
]);
$customer_details->details = $cust_details;
$customer_details->save();
}
Try this with single database query
$profile_photo = $request->file('profile_photo');
$finalData = [];
$names = [];
$addresses = [];
$images = [];
for ($i=0; $i < count(request('profile_photo')); $i++) {
$pro_fileExt = $profile_photo[$i]->getClientOriginalExtension();
$pro_fileNameToStore = time().'.'.$pro_fileExt;
$pro_pathToStore = public_path('images');
Image::make($profile_photo[$i])->save($pro_pathToStore . DIRECTORY_SEPARATOR. $pro_fileNameToStore);
$profile_ph = '/images/'.$pro_fileNameToStore; }
$names[] = $request->input('name');
$addresses[] = $request->input('address');
$images[] = $profile_ph;
}
$cust_details=json_encode(['name' => $names, 'address' => $addresses, 'images' => $images]);
$customer_details->insert($cust_details);

Persisting data to database. persist not working

I wrote a controller action that is supposed to add an element (meeting) to the database here it is:
public function newAction(Request $request){
$meeting = new Meeting();
$meetingUser = new MeetingUser();
$project = new Project();
$projectName = "SocialPro";//$request->get('projectName');
echo($projectName);
$users = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findProjectUser($projectName);
//$form = $this->createForm('SocialPro\MeetingBundle\Form\MeetingType', $meeting);
//$form->handleRequest($request);
//if ($form->isSubmitted() && $form->isValid()) {
$userconn = $this->container->get('security.token_storage')->getToken()->getUser();
echo($userconn->getId());
if ($request->isMethod('POST')) {
echo("message form");
$role = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findUserRole($userconn)[0]['role'];
$date = $request->get('date');
if ($role == "PROJECT_MASTER" || $role == "TEAM_MASTER") {
for ($i = 0; $i < count($users); $i++) {
$meetings = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findMeetingUser($users[$i]['id'], $date);
}
if ($meetings == null || count($meetings) == 0) {
$project = $this->getDoctrine()->getRepository('SocialProProjectBundle:Project')->findBy(array("name" = >$projectName));
$meeting->setDescription($request->get('description'));
$meeting->setDate(new \DateTime($request->get('date')));
$meeting->setTime($request->get('time'));
$meeting->setProjectName($request->get('projectName'));
$meeting->setProject($project[0]);
$meetingUser->setMeetings($meeting);
$meetingUser->setUsers($userconn);
var_dump($meetingUser);
$meeting->setMeetingUser(array($meetingUser));
//$project->setMeetings($meeting->getId());
$em = $this->getDoctrine()->getManager();
$em->persist($meeting);
$em->persist($meetingUser);
$em->flush();
// $meetingUser->setUsers($request->get(''));
return $this->redirectToRoute('reunion_show', array('id' = > $meeting->getId()));
}
else {
echo("Membre indisponible");
}
}
else {
echo("Must be MASTER to create meeting");
}
}
return $this->render('SocialProMeetingBundle::ajoutMeeting.html.twig', array('users' = >$users));
// $em = $this->getDoctrine()->getManager();
//$em->persist($meeting);
//$em->flush($meeting);
// return $this->redirectToRoute('meeting_show', array('id' => $meeting->getId()));
//}
//return $this->render('SocialProMeetingBundle:ajouMeeting', array(
// 'meeting' => $meeting,
//'form' => $form->createView(),
//));
}
When I submit the form it gives me a site not available page. I tested it line by line and everything is working perfectly. Turns out the problem is in the
$em->persist($meeting);
And I have no idea how to fix it.
You must call flush immediately after calling persist like so:
$em->persist( $meeting );
$em->flush();
$em->persist( $meetingUser );
$em->flush();
Then it will persist both.

Cakephp 3: how to implement events in helper

in Cakephp 3 im trying to implement events in the helper class, this is example of what im trying to do:
protected $_View;
public function __construct(View $View, $config = [])
{
//debug($View);die;
$this->_View = $View;
parent::__construct($View, $config);
$this->_setupEvents();
}
/**
* setup events
*/
protected function _setupEvents() {
$events = [
'filter' => [$this, 'filter'],
];
foreach ($events as $callable) {
$this->_View->eventManager()->on("Helper.Layout.beforeFilter", $callable);
}
}
public function filter(&$content, $options = array()) {
preg_match_all('/\[(menu|m):([A-Za-z0-9_\-]*)(.*?)\]/i', $content, $tagMatches);
for ($i = 0, $ii = count($tagMatches[1]); $i < $ii; $i++) {
$regex = '/(\S+)=[\'"]?((?:.(?![\'"]?\s+(?:\S+)=|[>\'"]))+.)[\'"]?/i';
preg_match_all($regex, $tagMatches[3][$i], $attributes);
$menuAlias = $tagMatches[2][$i];
$options = array();
for ($j = 0, $jj = count($attributes[0]); $j < $jj; $j++) {
$options[$attributes[1][$j]] = $attributes[2][$j];
}
$content = str_replace($tagMatches[0][$i], $this->menu($menuAlias, $options), $content);
}
return $content;
}
But im getting warning for the line where im calling constructor of parent Helper class:
Warning (4096): Argument 1 passed to App\View\Helper\MenusHelper::__construct() must be an instance of App\View\Helper\View, instance of App\View\AppView given, called in C:\wamp\www\CookieCMS\vendor\cakephp\cakephp\src\View\HelperRegistry.php on line 142 and defined [APP/View\Helper\MenusHelper.php, line 26]
Is it possible to implement events in helper this way and what is it that im doing wrong?
The Helper class is already implements EventlistenerInterface, so as explained in the manual all you have to do in your custom helper is return a proper array with required event name to callback mapping from implementedEvents() method.
So something like:
public function implementedEvents()
{
$mapping = parent::implementedEvents();
$mapping += [
'Helper.Layout.beforeFilter' => 'someMethodOfYourHelper',
];
return $mapping;
}

Why multiple records is not updating using cakephp?

I am giving my controller code below :
for ($i = 0; $i < count($club_open); $i++) {
$infomation["ClubOpenDay"]["club_id"] = $club_id;
$infomation["ClubOpenDay"]["days"] = $club_open[$alpha[$i]];
$infomation["ClubOpenDay"]["open_time"] = $club_open_time[$alpha[$i]];
$infomation["ClubOpenDay"]["close_time"] = $club_close_time[$alpha[$i]];
$infomation["ClubOpenDay"]["status"] = $club_status[$alpha[$i]];
$this->ClubOpenDay->updateAll(
array('ClubOpenDay.status' => "'".$infomation["ClubOpenDay"]["status"]."'"),
array('ClubOpenDay.club_id' => "'".$club_id."'")
);
}
using this code, I am not able to update multiple records. Any idea?
instead of this:
$this->ClubOpenDay->updateAll(
array('ClubOpenDay.status' => "'".$infomation["ClubOpenDay"]["status"]."'"),
array('ClubOpenDay.club_id' => "'".$club_id."'")
);
write the following:
$this->ClubOpenDay->updateAll(
array('ClubOpenDay.status' => $infomation["ClubOpenDay"]["status"]),
array('ClubOpenDay.club_id' => $club_id)
);

Resources