In the get_all_staff(), I would like to get the company's staffs list based on the cnditions i have defined, but for example 'role !='=>'Management Office', is not working , and if I change its place in the code , it would works but the other condition will not work, what I am trying to say is all the syntax are correct, but all the conditions are not working in the same tiem.
public function get_all_staff($company_name)
{
// $query = $this->db->get_where('user_login', array('company_name' => $company_name,'role !='=>'Manager','delete_flag'=>0,'role !='=>'Management Office' , 'role !='=>'Admin'));
$query = $this->db->get_where('user_login', array('company_name' => $company_name,'role !='=>'Management Office','role !='=>'Manager','delete_flag'=>0 ,'role!='=>'Admin'));
return $query->result();
}
try like this.
public function get_all_staff($company_name)
{
$this->db->where('company_name', $company_name);
$this->db->where('role !=', 'Management Office');
$this->db->where('role !=', 'Manage');
$this->db->where('role !=', 'Admin');
$this->db->where('delete_flag', '0');
return $this->db->get('user_login')->result_array();
//if there is only one row then do it
// return $this->db->get('user_login')->row_array();
}
Related
Hello everyone I have this problem with the Models and Map in Laravel:
I have a code that is more or less like this:
public function getProducts()
{
$products = Product::selectRaw('
products.id,
products.name
');
return $products->paginate(15);
}
public function parseProducts()
{
$data = $this->getProducts();
$data->map(function ($item) {
$item->id = $this->encrypt($item->id);
return $item;
});
return $data;
}
The encryption code works fine but in this loop it doesn't, it returns all ids with 0.
If I use DB::table("products") instead of Product everything works fine.
Will there be any blockage?
Trying to optimise my code and not have a bunch of if statements and converting to using 'when'.
Old code was as follows (worked fine):
$bursary_administrator = BursaryAdministrator::findOrFail(\Auth::user()->userable_id);
$search = $request->search;
if($search == ''){
$students = $bursary_administrator->students()
->select('students.id',DB::raw("CONCAT(student_name,' ',student_middle_names,' ',student_surname) AS `student_complete_name`"))
->orderby('student_complete_name','asc')->get();
}else{
$students = $bursary_administrator->students()
->select('students.id',DB::raw("CONCAT(student_name,' ',student_middle_names,' ',student_surname) AS `student_complete_name`"))
->whereraw("CONCAT(student_name,' ',student_middle_names,' ',student_surname) like ?",['%'.$search.'%'])
->orderby('student_complete_name','asc')->get();
}
Then I converted to using 'when' and also added an extra condition (active):
$bursary_administrator = BursaryAdministrator::findOrFail(\Auth::user()->userable_id);
$students = $bursary_administrator->students()->select('students.id',DB::raw("CONCAT(student_name,' ',student_middle_names,' ',student_surname) AS `student_complete_name`"));
$students->when(request('search') != '', function ($q) {
return $q->whereraw("CONCAT(student_name,' ',student_middle_names,' ',student_surname) like ?",['%'.request('search').'%']);
})->when(request('active') == true, function ($q) {
return $q->whereIn('status',[1,4,6,7]);
});
$students->orderby('student_complete_name','asc')->get();
$response = array();
foreach($students as $student){
$response[] = array(
"id"=>$student->id,
"text"=>$student->student_complete_name
);
}
However, getting errors (the below is from tinker testing):
PHP Notice: Trying to get property 'id' of non-object in Psy Shell code on line 2
PHP Notice: Trying to get property 'student_complete_name' of non-object in Psy Shell code on line 2
What have I done wrong? I was folowing https://laraveldaily.com/less-know-way-conditional-queries/ and the difference is that there they were using a query, and I used it 'directly' on the model?
Ok, your problem is you are trying to loop an QueryBuilder and not the results of it. Which you do not assign to anything.
$students->orderby('student_complete_name','asc')->get();
To fix it.
$students = $students->orderby('student_complete_name','asc')->get();
But wait, there is more. I think you can make this a little more clear.
In your when boolean statements, not equal empty string, is equivalent to just checking the string as (bool) $string. Way more readable secondly, PHP's type juggling will convert a lot of cases to true. So if active is any string unless 0, it will return true.
Instead of making a transformation array, let Laravel handle the transformation. Make your calculated name, as an accessor and add it to the response with appends. Therefor in your Student.php model. Add the following.
class Student {
protected $appends = ['name'];
public function getNameAttribute(): string
{
return $this->attributes['student_complete_name'] ?? '';
}
}
Now you whole code can be as simple as.
$bursary_administrator = BursaryAdministrator::findOrFail(\Auth::user()->userable_id);
$students = $bursary_administrator->students()->select('students.id',DB::raw("CONCAT(student_name,' ',student_middle_names,' ',student_surname) AS `student_complete_name`"));
$students->when(request('search'), function ($q) {
return $q->whereraw("CONCAT(student_name,' ',student_middle_names,' ',student_surname) like ?",['%'.request('search').'%']);
})->when(request('active') === '1', function ($q) {
return $q->whereIn('status',[1,4,6,7]);
});
return $students->orderby('student_complete_name','asc')->get();
This will be obvious to someone else
I have a route that works and goes to the correct controller
Route::get('v1/holidays/{country}/{year}/{month}/{official?}',
'retrieveHolidayController#test'
so if i go to
http://example.com/v1/holidays/US/2014/03/01
it will go where I want to go
however I want the link to look like
http://example.com/v1/holidays?country=US&year=2014&month=03&official=01
How can I do this please ?
You redefine your route to
Route::get('v1/holidays', 'retrieveHolidayController#test');
Then in your controller you can get the param values with $request
public function test(Request $request)
{
if ( $request->has('country') && $request->country != '') {
$country = $request->country;
}
if ( $request->has('year') && $request->year != '') {
$year = $request->year;
}
.... // and the others. Then you can query like this
$holidays = Holiday::when($country, function($query) use ($country) {
return $query->where('country', $country);
})
->when($year, function($query) use ($year) {
return $query->where('year', $year);
})
->get();
//Using 'when' only executes the closure if the variable exists
}
Now, you can use your URL just the way you wanted: http://example.com/v1/holidays?country=US&year=2014&month=03&official=01
Make country,year and monthalso optional:-
Route::get('v1/holidays/{country?}/{year?}/{month?}/{official?}', 'retrieveHolidayController#test')
Route::get('v1/holidays', 'retrieveHolidayController#test');
Route::get('v1/holidays/{country}/{year}/{month}/{official?}', function($country){
return redirect()->to(action('retrieveHolidayController#test', ["country"=>$country,......]));
});
access to http://example.com/v1/holidays/US/2014/03/01
redirect to http://example.com/v1/holidays?country=US&year=2014&month=03&offical=01
if official param is null redirect param offical= param is nullable
not feel good
so
isset($official){
$paramArry["official"] = $official;
}
I'm using Laravel Excel from maatwebsite but i have a problem with export data to xls file. I have this query but i don't need to show all columns in the xls file but i need to select all this columns to do operations before download the file. In my select i have 8 columns but in my headers i just have 7 to show but this doesn't work because the 8ª column appears too.
MY FUNCTION:
public function toExcel($id) { $b = Budget::find($id);
$budget = Budget_Item::join('budgets', 'budget__items.id_budget', '=', 'budgets.id')
->join('items_sizes', 'budget__items.id_itemSize', '=', 'items_sizes.id')
->join('items', 'items_sizes.id_item', '=', 'items.id')
->join('material_types', 'items_sizes.id_materialType', '=', 'material_types.id')
->select('items.reference AS Referência', 'items.name AS Descrição', 'items_sizes.size AS Tamanho', 'material_types.material_type AS Material', 'budget__items.amount AS Quantidade', 'items_sizes.unit_price AS Val.Unitário', 'budget__items.price AS Val.Total', 'budget__items.purchasePrice')
->where('id_budget', '=', $id)
->get();
$budgetUpdate = [];
$budgetUpdate[] = ['Referência', 'Descrição', 'Tamanho', 'Material', 'Quantidade', 'Val.Unitário', 'Val.Total'];
foreach ($budget as $key)
{
if ($key->purchasePrice > 0)
{
$key->unit_price = $key->purchasePrice;
}
$budgetUpdated[] = $key->toArray();
}
Excel::create('Proposta_'.$b->reference, function($excel) use($budgetUpdated)
{
// Set the title
$excel->setTitle('Proposta');
$excel->sheet('Sheetname', function($sheet) use($budgetUpdated)
{
$sheet->fromArray($budgetUpdated, null, 'A1', false, true);
});
})->download('xls');}
How can i solve that?
Thank's
Tested on Laravel excel 3.1 docs
on controller
public function exportAsCsv()
{
return Excel::download(new MyExport, 'invoices.xlsx');
}
on MyExport, look at the map function
class MyExport implements FromCollection, WithHeadings, WithMapping{
public function collection(){
return MyTable:all();
}
// here you select the row that you want in the file
public function map($row): array{
$fields = [
$row->myfield2,
$row->myfield1,
];
return fields;
}
}
also check this
For what its worth I ran into a similar issue and didnt find much in terms of a fix so heres my solution.
1. I query the DB in the callback and get all the data I need.
2. I then go over the collection and create a new array on each iteration and assign a value & header. Works great for picking out columns from a model
Excel::create('User List Export', function($excel) {
$excel->sheet('Users', function($sheet) {
$email = yourModelGoesHere::all();
foreach ($email as $key => $value) {
$payload[] = array('email' => $value['email'], 'name' => $value['name']);
}
$sheet->fromArray($payload);
});
})->download('xls');
You can try this way.
$user_id = Auth::user()->id
Excel::create('User', function($excel) use ($user_id){
$excel->sheet('Sheet', function($sheet) use($user_id){
$user = User::where('user_id', $user_id)->select('name', 'email', 'role', 'address')->get();
});
})->export('xls');
return redirect('your route');
I've searched the ends of the earth and back for this solution, and for everyone else, the fix was to autoload the database class in autoload.php. However, I am already doing this, so I don't know where else to go with it.
Controller:
class Login extends CI_Controller{
function validate_credentials(){
$this->load->model('membership_model');
// call the member function from membership_model.php
$q = $this->membership_model->validate();
if($q){
// user info is valid
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area');
}else{
$this->index();
}
}
}
Model:
class Membership_model extends CI_Model{
function validate(){
// this method is called from the login.php controller
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$q = $this->db->get('members');
if($q->num_rows == 1){
return true;
}
return false;
}
}
Any help on this please, I'm going round in circles with this
My next thought is that php.ini needs configuring on my host server, to load the mysql modules - but I would very surprised by this?
Just to clarify - the line:
if($q->num_rows)
Is the problem, saying that I am trying to reference a property of a non object
Actually
if($q->num_rows)
should be
if($q->num_rows()) // It returns the number of rows returned by the query.
So you can use
if($q->num_rows()) // In this case it'll be evaluated true if rows grater than 0
{
// code when rows returned
}
num_rows is a function.
if ($query->num_rows() > 0) {
}
So you need
if($q->num_rows() > 0) {
return true;
}
Solved - I hadn't assigned a User to the database, therefore couldn't access it.
Relief