How to store session id with request all? - php

I'm trying to save the passed course_id into lesson form in a DRY format.
I've tried saving each variable individually and it worked, however when I try to DRY up the code it is not working. Here is the code That I've tried.
public function store(StoreLessonsRequest $request)
{
if (! Gate::allows('lesson_create')) {
return abort(401);
}
$request = $this->saveFiles($request);
$lesson = Lesson::create($request->all() +
$lesson->course_id = session()->get('id') +
+ ['position' => Lesson::where('course_id', $request->course_id)->max('position') + 1]);
foreach ($request->input('lesson_materials_id', []) as $index => $id) {
$model = config('medialibrary.media_model');
$file = $model::find($id);
$file->model_id = $lesson->id;
$file->save();
}
return redirect()->route('admin.exams.create', ['course_id' => $request->course_id]);
}
I expected the course_id to save, but is giving me an error of Unsupported operand types.

Here is how I finally solved it. First I've declared the variable then I've passed it through.
public function store(StoreLessonsRequest $request)
{
if (! Gate::allows('lesson_create')) {
return abort(401);
}
$request = $this->saveFiles($request);
$seesion = session()->get('id');
$lesson = Lesson::create($request->all()
+ ['position' => Lesson::where('course_id', $request->course_id)->max('position') + 1] + ['course_id' => $seesion] );
foreach ($request->input('lesson_materials_id', []) as $index => $id) {
$model = config('medialibrary.media_model');
$file = $model::find($id);
$file->model_id = $lesson->id;
$file->save();
}

Related

Add to each array element another element php

I'm having one more problem in the logical realm.
I have an array containing ids:
$product_ids = ['1', '5', '3']; <- Example
Another string that I convert to an array separating it by commas, this to indicate the quantities of the products to be withdrawn. For example for product 1 I want 3 drives so I would need the array element to be "1,3".
$finalarray = ["1,3", "5,2", "3,10"];
Next I indicate the code that is executed in the controller (where is what I previously told):
public function ordenform(Request $request)
{
$input = $request->all();
$request->validate([
'nombre' => 'required|string',
'apellido' => 'required|string',
'productos' => 'required',
'cantidades' => 'required|string',
'enviosino' => 'required|in:si,no',
]);
// Quantity Array
$cantidades = explode(',', $input['cantidades']);
if (count($cantidades) != count($input['productos'])) {
return back()->withErrors(['Las cantidades no corresponden a los productos agregados']);
}
$total = 0;
$ganancia = 0;
foreach ($input['productos'] as $producto) {
$producto = Product::find((int) $producto);
$total += $producto->value;
$ganancia += $producto->ganancia;
$producto->stock = (int) $producto->stock - 1;
$producto->save();
}
if ($input['enviosino'] == 'si') {
$total += (int) $input['envio'];
}
if ($input['envio'] == null) {
$input['envio'] = 0;
}
// Products IDS Array
$jsonproductos = json_encode($input['productos']);
Order::create([
'nombre' => $input['nombre'],
'apellido' => $input['apellido'],
'product_ids' => $finalprods,
'value' => $total,
'ganancia' => $ganancia,
'envio' => $input['envio'],
]);
$caja = Config::where('id', 1)->get()->first();
$caja->dinerototal += $total;
$caja->gananciatotal += $ganancia;
$caja->save();
return back()->with('success', 'Orden creada correctamente');
}
Finally, I need to pass as creation parameter the final array to the column products_ids (later I will modify the name).
Another option I thought of is passing objects to an array:
[{id: 1, quantity: 3}]
But I don't know how to get to create that object, I'm still kind of new hehe.
I hope I have explained myself well, English is not my native language. I'm sorry.
I am attentive to your comments !! Greetings.
PS: I am using Laravel
To achieve [{id: 1, quantity: 3}] there will be several idea, but it seems to be an arrayList, so below is how you can create an arrayList in PHP. I have not tested the code, just written here, but should give you the idea to achieve this.
I am considering one is Order class.
<?php
class Order {
private $id;
private $quantity;
public function setId(int $id) {
$this->id = $id;
return $this;
}
public function getId(){
return $this->id;
}
public function setQuantity(int $quantity) {
$this->quantity = $quantity;
return $this;
}
public function getQuantity(){
return $this-> quantity;
}
public function toArray(){
return [
'id' => $this->getId(),
'quantity' => $this->getQuantity()
];
}
}
?>
another is OrderList.
<?php
class OrderList {
private $orderList;
public function __construct(Order ...$orders) {
$this->orderList = $orders;
}
public function toArray(){
$arr = [];
foreach ($this->orderList as $order) {
$arr[] = $order->toArray();
}
return $arr;
}
}
?>
and then use like
$order1 = new Order();
$order1 = $order1->setId(1)->setQuantity(10);
$order2 = new Order();
$order2 = $order1->setId(2)->setQuantity(20);
$orderList = new OrderList($order1, $order2);
var_dump(json_encode($orderList->toArray()));
//Output
string(47) "[{"id":2,"quantity":20},{"id":2,"quantity":20}]"
You do not need json_encode, I have added it to print only.
Nevermind, resolved ->
$prodsfinal = array();
for ($i = 0; $i < sizeof($cantidades); $i++) {
$array = [
'id' => json_decode($input['productos'][$i]),
'cantidad' => (int) $cantidades[$i],
];
array_push($prodsfinal, $array);
}

How to fix my "Notice: Undefined offset: 4" error

I have a problem with my code, when a User have all "stations" the code work but if he dont have one i have the (undefined offset *) error,
my code look like that ( in my controller )
public function index()
{
$entityManager = $this->getDoctrine()->getManager();
$stations = $this->getListOfStations();
$stationsJson = [];
$events = $entityManager->getRepository('App:User')
->getEventInRealTime($this->getUser());
foreach ($stations as $station) {
$stationsJson[] = [
'typeEvents' => $events[$station->getId()],
];
}
return new JsonResponse(array('stations' => $stationsJson));
}
private function getListOfStations()
{
/** #var UserInterface $user */
$user = $this->getUser();
$entityManager = $this->getDoctrine()->getManager();
if (!$this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
$stations = $user->getStations();
} else {
$stations = $entityManager->getRepository('App:Station')->findAll();
}
return $stations;
}
and my repository
public function getEventInRealTime($user)
{
$qb = $this->createQueryBuilder('u');
$events = $qb
->select('s.id as stationId, COUNT(e) as number, e.label as type')
->innerJoin('u.stations', 's')
->innerJoin('s.events', 'e')
->where('u = :user')
->setParameter('user', $user)
->andWhere('DAY(e.currentTime) =:day')
->setParameter('day', date('d'))
->andWhere('MONTH(e.currentTime) =:month')
->setParameter('month', date('m'))
->andWhere('YEAR(e.currentTime) =:year')
->setParameter('year', date('Y'))
->groupBy('s.id, type');
$data = $events->getQuery()->getArrayResult();
$result = [];
foreach ($data as $row) {
$result[$row['stationId']][] =
[
'number' => $row['number'],
'type' => $row['type']
];
}
return $result;
}
i think its a problem its like, he dont find the "stations" when i do a findAll(), but i dont know how to fix it, when the user is super_admin he can have see all the stations but if is not super admin he can see only his stations

In laravel in controller pass variable to one function to another function

I am coding in Laravel, How can I pass variable to one function to another function in Controller,
In controller file I have 2 functions like this
public function hiringEmployee(Request $request)
{
$hireEmployee = new EmployeeHire();
$hireEmployee->candidateName = $request->get('candidateName');
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/cv', $name);
$hireEmployee->file = $name;
$hireEmployee->save();
return redirect('list-candidate');
}
public function assignInterview(Request $request, $id)
{
$assignInterview = EmployeeHire::find($id);
$interview = $request->get('interview');
$assignto = $request->get('assignto');
$dateTime = $request->get('dateTime');
$note = $request->get('note');
$interviewDetails = ([
'interview' => $interview,
'assign_to' => $assignto,
'date_time' => $dateTime,
'note' => $note,
]);
$assignInterview->interview_details = $interviewDetails;
$assignInterview->save();
Mail::send('emails.hireemployee', ['candidateName' => $candidateName], function ($message) use ($assignto, $name) {
$message->subject('Interview For New Candidate!');
$message->from('hrm#wcg.com', 'HRM');
$message->to($mail);
$message->attach('uploads/cv/'.$name);
});
return redirect('list-candidate');
}
I want to use $candidateName and $name in assignInterview() function from hiringEmployee() function.
How can I do it?
You won't be able to use the $name and $candidateName directly from the other function as they look like they are for two different requests, however, it looks like you're saving that data to database when you're creating a new EmployeeHire in your hiringEmployee() method so you should already have access to that information in your assignInterview() method:
$assignInterview = EmployeeHire::find($id); // this is where you loading the model
$candidateName = $assignInterview->candidateName;
$name = $assignInterview->file;
In your situation , you can use two approach:
#1
Use Session Variable as below:
Session::put('candidateName', $candidateName);
Then:
$value = Session::get('candidateName');
#2
Use class attribute:
class acontroller extends Controller
{
private $classCandidateName;
}
You can try something like this:
public function hiringEmployee(Request $request)
{
$hireEmployee = new EmployeeHire();
$hireEmployee->candidateName = $request->get('candidateName');
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/cv', $name);
$hireEmployee->file = $name;
$hireEmployee->save();
return redirect('list-candidate');
}
public function assignInterview(Request $request, $id)
{
$assignInterview = EmployeeHire::find($id);
if(is_null($assignInterview)){
return redirect()->back()->withErrors(['Error message here']);
}
$interviewDetails = ([
'interview' => $request->get('interview'),
'assign_to' => $request->get('assignto'),
'date_time' => $request->get('dateTime'),
'note' => $request->get('note'),
]);
$assignInterview->interview_details = $interviewDetails;
$assignInterview->save();
Mail::send('emails.hireemployee', ['candidateName' => $assignInterview->candidateName], function ($message) use ($assignto, $assignInterview->file) {
$message->subject('Interview For New Candidate!');
$message->from('hrm#wcg.com', 'HRM');
$message->to($mail);
$message->attach('uploads/cv/'.$assignInterview->file);
});
return redirect('list-candidate');
}
Please, you should to be careful with find($id). If it is a null, you will get an error.
Have fun!

Laravel Increase SQL speed

I am trying to increase the speed of my queries in Laravel 5.7 and I have the call down to ~2.5 seconds. I am trying to figure out more ways to make it faster and if I could get some help I'd greatly appreciate it.
Thanks
How my data is structured:
Function(Controller):
public function getUserDataTmp(Request $request) {
$input = file_get_contents("php://input");
$request = json_decode($input);
if ($this->authTokenAccess($request) == true) {
$bottomWords = bottom_exterior_word::select('word','sentence','sequence','id','group_id')->where('user_id','=', $request->id)->get();
$emergencyWords = left_exterior_word::select('word','sentence','sequence','id')->where('user_id','=', $request->id)->get();
foreach($bottomWords as $tmp => $key) {
$group_id = $key->group_id;
$bottomWords->user_id = $request->id;
$bottomWords[$tmp]->words = $key->getMainWords($group_id, $request->id);
}
foreach($emergencyWords as $key => $word) {
$emergencyWords[$key]->image = imageModel::select('base64','id')->where('emergency_id','=', $word->id)->first();
}
$data = [
'data' => [
'return' => 'success',
'code' => 'VEDC001',
'response' => 'Successfully Gathered Words',
'main_categories' => $bottomWords,
'emergency_words' => $emergencyWords
]
];
return(json_encode($data));
}
}
getMainWords Function(bottom_exterior_word model):
public function getMainWords($group_id, $id)
{
// return("TEST");
$words = \App\main_word::select('id','group_id','sentence','sequence','word')->where('group_id','=', $group_id)->where('user_id','=', $id)->get();
foreach ($words as $key => $word) {
$words[$key]->image = Image::select('base64','id')->where('word_id','=', $word->id)->first();
}
return $words;
}
Start by refactoring so that you dont query inside a foreach loop
foreach($bottomWords as $tmp => $key) {
$group_id = $key->group_id;
$bottomWords->user_id = $request->id;
$bottomWords[$tmp]->words = $key->getMainWords($group_id, $request->id);
}
I would change the getMainWords function to accepts an array of group id's and use the whereIn clause:
The whereIn method verifies that a given column's value is contained
within the given array:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
Same treatment for this loop.
foreach($emergencyWords as $key => $word) {
$emergencyWords[$key]->image = imageModel::select('base64','id')->where('emergency_id','=', $word->id)->first();
}
In general minimizing the NUMBER of queries will improve response time.
Old post, would just like to update it though. Since I have first posted this, I have learned a lot more about Laravel and am a lot more experienced with it.
Here is my new function and solution:
Controller:
public function data(Request $request)
{
return response()->success(
[
'emergencywords' => EmergencyWord::with('image')->whereUserId($request->user()->id)->get(),
'categorywords' => CategoryWord::with(['image','words.image'])->whereUserId($request->user()->id)->get(),
]
);
}
Category Word Relationships:
public function image()
{
return $this->hasOne('App\Image','id','image_id');
}
public function words()
{
return $this->hasMany('App\MainWord','category_words_id','sequence');
}
Emergency Word Relationships:
public function image()
{
return $this->hasOne('App\Image','id','image_id');
}
Main Word Relationships:
public function image()
{
return $this->hasOne('App\Image','id','image_id');
}

Upload CSV to SQL using laravel eloquent

I have this problem in uploading my csv to my database (SQL). I am using Maatwebsite... And here's is my controller:
class UploadCSV extends Controller
{
public function store(Request $request){
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['s_id' => $value->id,
'school_name' => $value->sname,
'region' => $value->reg,
'province' => $value->prov,
'municipality' => $value->mun,
'division' => $value->div,
'district' => $value->dis,
'enrollment_sy_2014_2015' => $value->enrolled,
'mooe_in_php_for_fy_2015' => $value->mooe,
'latitude' => $value->lat,
'longitude' => $value->lng
];
}
Map::insert($arr);
dd('Insert Record successfully.');
//return json_encode($arr);
}
}
dd('Request data does not have any files to import.');
}
Which gives me this endless error message:
The CSV contains only 200+ rows. Any help would be appreciated. Thanks in advance :))
Maybe try something like this, create new Model (assuming Map is the name of your Model and save():
<?php
class UploadCSV extends Controller
{
public function store(Request $request){
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$entry = new Map;
$entry->s_id = $value->id;
$entry->school_name = $value->sname;
$entry->region = $value->reg;
$entry->province = $value->prov;
$entry->municipality = $value->mun;
$entry->division = $value->div;
$entry->district = $value->dis;
$entry->enrollment_sy_2014_2015 = $value->enrolled;
$entry->mooe_in_php_for_fy_2015 = $value->mooe;
$entry->latitude = $value->lat;
$entry->longitude = $value->lng;
$entry->save();
}
}
}
dd('Request data does not have any files to import.');
}
}

Categories