Been trying to resolve this query for a long time now, it's working but there is a bit of misquery.
This is one of my queries from my search function with livewire.
return empty($search)
? static::query()
: static::query()->where('id','like','%'.$search.'%')
->orWhereHas('status.user',function($q) use ($search){
$q->where('active',1)
->where('name','like','%'.$search.'%')
->orWhere('username','like','%'.$search.'%');
});
For example, I type the name of 'jason' the query will return the correct result, but if I type Jason's username it will return every record that Jason's been update (but not active) I just want the action to return with a particular name or username.
I already try to separate the active, name, and username on different functions but the result is the same.
AND has precedence over OR so this condition
$q->where('active',1)
->where('name','like','%'.$search.'%')
->orWhere('username','like','%'.$search.'%');
is evaluating like - where ( active = 1 and name like '%$search%' ) or username like '%$search%'
But if I am not wrong then your want something like where active = 1 and ( name like '%$search%' or username like '%$search%')
To achieve this you can try segregating above condition like -
$q->where('active',1)
->where(function($q2) use ($search){
$q2->where('name','like','%'.$search.'%')
$q2->orWhere('username','like','%'.$search.'%');
});
Please let me know if it worked.
I used this query to update the status column.
$val="1";
vehicles::where('id' , '=' , $veh_status)->update(['status' => $val]);
But when I submitted the status value doesn't change.
you can trace your query by using ->toSql() method !
try this to find whats happening in back
Not sure what the problem is there because you haven't given much info to work with, but you can check these suggestions:
Check if the column is set to be mass assignable in the model class, that is, it is in the fillable[] array.
make sure the id you pass to the where() function is valid.
Try using another function, save() which will achieve the same results you seek, like this;
// filter the vehicle
$vehicle = vehicles::where('id', '=', $veh_id)->first();
or
$vehicle = vehicles::find($veh_id);
$vehicle->status = 1;
$vehicle->save();
Lastly, I noticed your id variable you pass to the where the () function is called $veh_status "presumably - vehicle status" and not $veh_id, "presumably - vehicle id" so probably check that out.
Ref: Laravel Model Update documentation
I have this basic query i want to perform but an error keeps coming up. Probably due to my newness to laravel.
here is the code:
$userRecord = $this->where('email', $email)->where('password', $password);
echo "first name: " . $userRecord->email;
I am trying to get the user record matching the credentials where email AND password are a match. This is throwing an error:
Undefined property: Illuminate\Database\Eloquent\Builder::$email
I've checked the email and password being passed to the function, and they are holding values. what is the problem here?
Thanks,
$this->where('email', $email)->where('password', $password)
is returning a Builder object which you could use to append more where filters etc.
To get the result you need:
$userRecord = $this->where('email', $email)->where('password', $password)->first();
You either need to use first() or get() to fetch the results :
$userRecord = $this->where('email', $email)->where('password', $password)->first();
You most likely need to use first() as you want only one result returned.
If the record isn't found null will be returned. If you are building this query from inside an Eloquent class you could use self .
for example :
$userRecord = self::where('email', $email)->where('password', $password)->first();
More info here
$userRecord = Model::where([['email','=',$email],['password','=', $password]])->first();
or
$userRecord = self::where([['email','=',$email],['password','=', $password]])->first();
I`
think this condition is better then 2 where. Its
where condition array in array of where conditions;
The error is coming from $userRecord->email. You need to use the ->get() or ->first() methods when calling from the database otherwise you're only getting the Eloquent\Builder object rather than an Eloquent\Collection
The ->first() method is pretty self-explanatory, it will return the first row found. ->get() returns all the rows found
$userRecord = Model::where('email', '=', $email)->where('password', '=', $password)->get();
echo "First name: " . $userRecord->email;
After reading your previous comments, it's clear that you misunderstood the Hash::make function. Hash::make uses bcrypt hashing. By design, this means that every time you run Hash::make('password'), the result will be different (due to random salting). That's why you can't verify the password by simply checking the hashed password against the hashed input.
The proper way to validate a hash is by using:
Hash::check($passwordToCheck, $hashedPassword);
So, for example, your login function would be implemented like this:
public static function login($email, $password) {
$user = User::whereEmail($email)->first();
if ( !$user ) return null; //check if user exists
if ( Hash::check($password, $user->password) ) {
return $user;
} else return null;
}
And then you'd call it like this:
$user = User::login('email#aol.com', 'password');
if ( !$user ) echo "Invalid credentials.";
else echo "First name: $user->firstName";
I recommend reviewing the Laravel security documentation, as functions already exist in Laravel to perform this type of authorization.
Furthermore, if your custom-made hashing algorithm generates the same hash every time for a given input, it's a security risk. A good one-way hashing algorithm should use random salting.
Here is shortest way of doing it.
$userRecord = Model::where(['email'=>$email, 'password'=>$password])->first();
$userRecord = $this->where('email', $email)->where('password', $password);
in the above code , you are just requesting for Eloquent object , not requesting for the data,
$userRecord = $this->where('email', $email)->where('password', $password)->first();
so that, you can get the first data, from the given credentials by default ordering DESC with PK, in case of multiple data with the same credentials. but you have to handle the exception, in case of no matching data.
you have one more option to achieve the same.
$userRecord = $this->where('email', $email)->where('password', $password)->firstOrfail();
in the above snippets, in case of no data, it will automatically throw a 404 error.
also, you can have alternative snippets
$filter['email']=$email;
$filter['password']=$password;
$userRecord = $this->where($filter)->first();
That's it
After rigorous testing, I found out that the source of my problem is Hash::make('password'). Apparently this kept generating a different hash each time. SO I replaced this with my own hashing function (wrote previously in codeigniter) and viola! things worked well.
Thanks again for helping out :) Really appreciate it!
I'm having problems to do a simple permission system on my Webapp. My DB has a table called "usuario" that has informations about the users of the system. One of these columns is called "privilegio" that has value '0' for administrators and 1 for regular users. An administrator has the power to Add and edit users on the system. Im trying to take this behavior querying my database with the cod of the logged user and getting its permission. If the user is not on the administrator group (privilegio=1) then the add/edit/delete buttons will be unset.
public function usuario() {
if($this->session->userdata('logged')){
$crud = new grocery_CRUD();
$crud->set_subject("Usuário");
$crud->set_theme('datatables');
$crud->set_table("usuario");
(...)
$crud->field_type('privilegio','dropdown',array('0'=>'Administrador','1'=>'Usuario'));
(...)
$this->db->select('privilegio');
$this->db->get('usuario');
$result = $this->db->where('cod_func',$this->session->userdata('cod_func'));
if(!$result){
$crud->unset_add();
$crud->unset_edit();
$crud->unset_delete();
}
(...)
The problem (and the question) is that this code only list the user that is logged on, not the others already registered on the system and stored on "usuario" table. I wonder that the list is been made by my query (what is not the behavior I would like) I hope you could undestand my doubt. Sorry for my bad english.
Thank you!
you're having trouble with the active record functions...
When you use the function
$this->db->get('usuario');
This translates to the query:
SELECT * FROM usuario
So try changing your code to something like this:
$this->db->select('privilegio');
$this->db->from('usuario');
$this->db->where('cod_func',$this->session->userdata('cod_func'));
$this->db->limit(1); //You're only expecting one result
$result = $this->db->get(); // Save the result to the variable result
//Edited for the comment, something like
$result = $result->first_row('array'); //Here I'm fetching only the first row into an array
$privilegio = $result['privilegio']; //Im saving the result from the query in the variable $privilegio
This translates to:
SELECT priviliegio FROM usuario WHERE cod_func = 'some_value' LIMIT 1;
Then you can do whatever you want with the $result variable, please refer to documentation to see what you can do...
Generating Query Results
I have a login system for my webapp that works well using the Zend auth adapter but the problem is I want the email to be case insensitive when a user logs in. I am using Oracle as the back end DB and normally I would user the LOWER(EMAIL)=LOWER(:email) method. I tried to pass that Oracle function in the setIdentityColumn() but I get the error:
The supplied parameters to Zend_Auth_Adapter_DbTable failed to produce
a valid sql statement, please check table and column names for
validity.
protected function _getAuthAdapter()
{
//$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$db = Zend_Registry::get('db');
$authAdapter = new Zend_Auth_Adapter_DbTable($db);
$authAdapter->setTableName('USER_TABLE')
->setIdentityColumn('LOWER(EMAIL)') //Tried to pass LOWER()
->setCredentialColumn('ENCODED_PW')
->setCredentialColumn('PASSWORD');
return $authAdapter;
}
The error is coming from the function _authenticateCreateSelect() in the Zend_Auth_Adapter_DbTable class. The problem is this part of the script:
$dbSelect->from($this->_tableName, array('*', $credentialExpression))
->where($this->_zendDb->quoteIdentifier($this->_identityColumn, true) . ' = ?', $this->_identity);
The quoteIdentifier() method is like PHP quote() and is turning a query like this:
select * from LOWER(:email)
into this:
select * from "LOWER(:email)"
Anyone see a way around this?
Kind Regards
Nathan
Try something like this:
$authAdapter->setTableName('USER_TABLE')
->setIdentityColumn(new Zend_Db_Expr('LOWER(USERID)'))
->setCredentialColumn('PASSWORD');
The problem is that if you pass 'LOWER(USERID)' as a simple string, Zend will put quotes around it, causing it to create an invalid query. Using Zend_Db_Expr will stop Zend doing this.