Is there a better way of organizing or writing the below controller method in Laravel 5.1?
I want to keep my Controllers short and sweet. I am using a repository setup as i'm building quite a large application and I want to keep everything organised.
Please advise on the best way to organise the below code.
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create(CreateTimesheetRequest $request)
{
$data = $request->only('user_id', 'template_id');
$data['submitted_by'] = Auth::user()->id;
$timesheetId = $this->timesheet->createTimesheet($data);
foreach($request->get('row') as $key => $row)
{
foreach($row as $field => $value)
{
$this->timesheet->saveTimesheetRows([
'timesheet_id' => $timesheetId,
'field_id' => $this->timesheetFields->where('name', $field)->first()->id,
'field_name' => $field,
'field_value' => $value,
'field_key' => $key
]);
}
}
return Redirect::back()->withMessage('The timesheet was successfully created.');
}
All I can suggest - move this:
$data = $request->only('user_id', 'template_id');
$data['submitted_by'] = Auth::user()->id;
... into yours request class. For example, into some data() method:
class CreateTimesheetRequest ... {
...
public function data() {
return array_merge(
$this->only('user_id', 'template_id'),
['submitted_by' => Auth::user()->id]
);
}
}
Also, $this->timesheet->saveTimesheetRows(array) looks more like $this->timesheet->saveTimesheetRow(array) for me - name intends to save multiple rows, but you feed that method only with one row per call.
Maybe, you can refactor that method to smth. like this:
function saveTimesheetRows($timesheetId, $key, $rows, $fieldIds) {
foreach($rows as $field => $value) {
$this->saveTimesheetRow([
'timesheet_id' => $timesheetId,
'field_id' => $fieldIds[$field],
'field_name' => $field,
'field_value' => $value,
'field_key' => $key
]);
}
}
function saveTimesheetRow(array $row) {
// old saveTimesheetRows implementation
}
Upd.
And another tip: use Eloquent's keyBy() method like so:
$keyIDs = $this->timesheetFields->whereIn('name', $fields)->get(["name", "id"])->keyBy("name");
So, finally:
public function create(CreateTimesheetRequest $request) {
$data = $request->data();
$timesheetId = $this->timesheet->createTimesheet($data);
foreach($request->get('row') as $key => $row) {
$this->timesheet->saveTimesheetRows(
$timesheetId,
$key,
$row,
$this->timesheetFields
->whereIn('name', array_keys($row))
->get(["name", "id"])
->keyBy("name") // probably, can be moved into $this->timesheetFields implementation
);
}
return Redirect::back()->withMessage('The timesheet was successfully created.');
}
Related
I have a problem that all the create-read-delete using Repository Pattern is good but the update function is error. I still have the data but the information is not updated.
This is my code in EventController
public function update(EventRequest $request, $id)
{
$events = $this->repository->update($request->all());
return $this->sendResponse($events->toArray(), 'Successfully updated the Event!!');
}
This is i use DI for inject from the Repository, this is EventRepository.php
public function update($id, array $array) {
$events = $this->model->findOrFail($id);
$events->update($array);
return $events;
}
when i use dd($array) and the result returns [] without anything. Can anyone help me. Did i write anything wrong in this. Or i write the wrong Request
public function rules()
{
// $id = $this->events ? ',' . $this->events->id : '';
return $rules = [
'event_title' => 'required|max:255',
'event_type_id' => 'required|integer|between:1,3',
'from_date' => 'required|date_format:Y-m-d H:i:s',
'to_date' => 'date_format:Y-m-d H:i:s|nullable',
'is_recurring' => 'boolean|required',
'remarks' => 'nullable',
];
}
This method takes two arguments:
public function update($id, array $array) {
However, that's not how you are calling it:
$this->repository->update($request->all());
I take it $request->all() gives you an array, so pass the ID first.
$this->repository->update($id, $request->all());
Trying to figure out why I am getting the following error:
Undefined index Plugin ID
I am using Maatwebsite\Excel for my import and tried using the guide here:
https://appdividend.com/2017/06/12/import-export-data-csv-excel-laravel-5-4/
I think I have everything in the right place, but I am getting the above error from this code:
public function import(Request $request)
{
if($request->file('imported-file'))
{
$path = $request->file('imported-file')->getRealPath();
$data = Excel::load($path, function($reader)
{
})->get();
if(!empty($data) && $data->count())
{
foreach ($data->toArray() as $row)
{
if(!empty($row))
{
$dataArray[] =
[
'plugin_id' => $row['Plugin ID'],
'cve' => $row['CVE'],
'cvss' => $row['CVSS'],
'risk' => $row['Risk'],
'host' => $row['Host'],
'protocol' => $row['Protocol'],
'port' => $row['Port'],
'name' => $row['Name'],
'synopsis' => $row['Synopsis'],
'description' => $row['Description'],
'solution' => $row['Solution'],
'see_also' => $row['See Also'],
'plugino_utput' => $row['Plugin Output']
];
}
}
if(!empty($dataArray))
{
Shipping::insert($dataArray);
return back();
}
}
}
}
This is in my controller file and is trying to account for the headers being different in the CSV compared to in my database.
Any idea why it would be complaining about index on a column from the csv side of things?
I ended up with this for now from another post. The post still had an extra section in it, but doing a var_dump on $value (which I left in, but commented out) I could see that $value was already an array, so instead of passing it into another array, I tried just inserting with it and that seems to be working.
Still working on placing the error and success messages.
Thanks to ljubadr for helping me learning how to put some print type statements in with the code to see what was getting output at various places.
public function importExcel(Request $request)
{
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {})->get();
if(!empty($data) && $data->count()){
foreach ($data->toArray() as $key => $value) {
if(!empty($value)){
#var_dump($value);
Item::insert($value);
}
}
return back()->with('success','Insert Record successfully.');
}
}
#return back()->with('error','Please Check your file, Something is wrong there.');
}
}
I use Maatwebsite/Laravel-Excel package to upload CSV to DB. Before entering data to DB i wanna do some additional checks with the database. Something like Project_id available in the Project table. Where do i write the required checking function. Is it a proper way to write it in the same controller. I have seen some people create folder In app\Example and write function file in it
UPDATE :
please let me know is this a proper way to do
https://www.youtube.com/watch?v=fS8q_sD1sZM
This the sample CSV format
This the controller function
public function uploadDealerCSV()
{
if(Input::hasFile('file')){
$path = Input::file('file')->getRealPath();
$data = Excel::load($path, function ($reader) {
$reader->ignoreEmpty();
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$insert[] = [
'project_id' => $value->project_id,
'dealer_bl_code' => $value->bl_code,
'reporgroup' => 104,
'added_by' => 73,
'updated_at' => '2017-08-08 10:34:54',
];
}
if(!empty($insert)){
DB::table('cts_project_list')->insert($insert);
//dd('Insert Record successfully.');
}
}
}
return back();
}
public function testFunction(){
}
I'm trying to create an Api using cakephp.
I generate a json on server and it works fine , but I tired to use pagination and I got a problem.
in the first case I take the image's path and I encode it to base64 and I generate json => works
in the second case I defined the pagination by the limits and the max and I kept the same code but as a result the image field is still the path from the database and it's not encoded
this my code in my controller :
class PilotsController extends AppController {
public $paginate = [
'page' => 1,
'limit' => 5,
'maxLimit' => 5
];
public function initialize() {
parent::initialize();
$this->loadComponent('Paginator');
$this->Auth->allow(['add','edit','delete','view','count']);
}
public function view($id) {
$pilot = $this->Pilots->find()->where(['Pilots.account_id' => $id], [
'contain' => ['Accounts', 'Pilotlogs']
]);
foreach ($pilot as $obj) {
if ($obj->image_pilot!= NULL) {
$image1 = file_get_contents(WWW_ROOT.$obj->image_pilot);
$obj->image_pilot = base64_encode($image1);
}
}
$this->set('pilot', $this->paginate($pilot));
$this->set('_serialize', ['pilot']);
}
}
If I remove the pagination from the code it works fine . Any idea how to fix it ??
I'd suggest to use a result formatter instead, ie Query::formatResults().
So you'll have something like this :
public function view($id) {
$pilot = $this->Pilots->find()
->where(['Pilots.account_id' => $id], [
'contain' => ['Accounts', 'Pilotlogs']]);
->formatResults(function($results) {
return $results->map(function($row) {
$image1 = file_get_contents(WWW_ROOT.$row['image_pilot']);
$row['image_pilot'] = base64_encode($image1);
return $row;
});
});
}
You can simply first paginate the data and then get the array values and after that modify that data as you want. Check this
public function view($id) {
$pilot = $this->Pilots->find()->where(['Pilots.account_id' => $id], [
'contain' => ['Accounts', 'Pilotlogs']
]);
$pilot = $this->paginate($pilot);
$pilot = $pilot->toArray();
foreach ($pilot as $obj) {
if ($obj->image_pilot!= NULL) {
$image1 = file_get_contents(WWW_ROOT.$obj->image_pilot);
$obj->image_pilot = base64_encode($image1);
}
}
$this->set('pilot', $pilot);
$this->set('_serialize', ['pilot']);
}
I'm new to Laravel and at the moment I have a piece of code in a Controller which without the while loop it works, it retrieves my query from the database.
public function dash($id, Request $request) {
$user = JWTAuth::parseToken()->authenticate();
$postdata = $request->except('token');
$q = DB::select('SELECT * FROM maps WHERE user_id = :id', ['id' => $id]);
if($q->num_rows > 0){
$check = true;
$maps = array();
while($row = mysqli_fetch_array($q)) {
$product = array(
'auth' => 1,
'id' => $row['id'],
'url' => $row['url'],
'locationData' => json_decode($row['locationData']),
'userData' => json_decode($row['userData']),
'visible' => $row['visible'],
'thedate' => $row['thedate']
);
array_push($maps, $product);
}
} else {
$check = false;
}
return response()->json($maps);
}
I am trying to loop through the returned data from $q and use json_decode on 2 key/val pairs but I can't even get this done right.
Don't use mysqli to iterate over the results (Laravel doesn't use mysqli). Results coming back from Laravel's query builder are Traversable, so you can simply use a foreach loop:
$q = DB::select('...');
foreach($q as $row) {
// ...
}
Each $row is going to be an object and not an array:
$product = array(
'auth' => 1,
'id' => $row->id,
'url' => $row->url,
'locationData' => json_decode($row->locationData),
'userData' => json_decode($row->userData),
'visible' => $row->visible,
'thedate' => $row->thedate
);
You're not using $postdata in that function so remove it.
Do not use mysqli in Laravel. Use models and/or the DB query functionality built in.
You're passing the wrong thing to mysqli_fetch_array. It's always returning a non-false value and that's why the loop never ends.
Why are you looping over the row data? Just return the query results-- they're already an array. If you want things like 'locationData' and 'userData' to be decoded JSON then use a model with methods to do this stuff for you. Remember, with MVC you should always put anything data related into models.
So a better way to do this is with Laravel models and relationships:
// put this with the rest of your models
// User.php
class User extends Model
{
function maps ()
{
return $this->hasMany ('App\Map');
}
}
// Maps.php
class Map extends Model
{
// you're not using this right now, but in case your view needs to get
// this stuff you can use these functions
function getLocationData ()
{
return json_decode ($this->locationData);
}
function getUserData ()
{
return json_decode ($this->userData);
}
}
// now in your controller:
public function dash ($id, Request $request) {
// $user should now be an instance of the User model
$user = JWTAuth::parseToken()->authenticate();
// don't use raw SQL if at all possible
//$q = DB::select('SELECT * FROM maps WHERE user_id = :id', ['id' => $id]);
// notice that User has a relationship to Maps defined!
// and it's a has-many relationship so maps() returns an array
// of Map models
$maps = $user->maps ();
return response()->json($maps);
}
You can loop over $q using a foreach:
foreach ($q as $row) {
// Do work here
}
See the Laravel docs for more information.