How to use Laravel elequent model to get data with mutiple where condition - laravel-5.1

I am new to Laravel and currently working on Laravel 5.1. I am trying to authenticate user by its email and password. To get this, I am using the below code to find the user:
First Method: Using Elequent Model
$result = user_model::where('email', $data['email'])->where('password', \Illuminate\Support\Facades\Hash::make($data['password']))->first();
Second Method: Using with() Method:
$result = user_model::where('email', $data['email'])
->where(function($q) use($data) {
$q->where('password', '=', Hash::make($data['password']));
})->first();
Third Method: Using query Builder:
$result = DB::table('users')->where('email', $data['email'])->where('password', Hash::make($data['password']))->get();
Each of the above method is returning null even the the user is exist into database.
If I use single where condition either for email or password then First method returns user object with data.
Can anyone help me for How can i get the result of query having multiple where conditions.

Related

Grails - how to display result page at a unique URL

I have a grails application that takes user input (create page/method), the user then clicks a Save button (save method that executes service) and then the results are displayed (list method) on a page, for example http://localhost:8080/myApp/myclass/save.
The users would like each results run to be saved to a unique URL so they can share it, bookmark it, save it later, whatever. I have NO idea how to go about this and google searches turn up little to nothing.
For example an application run would result in the data being displayed at http://localhost:8080/myApp/myclass/systemname/datetimestring/someuniquedata/
Is this even possible? Any pointers GREATLY appreciated.
EDIT
Here is my urlMappings contents.
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
"/" {
controller = "api"
action = "create"
}
"500"(view:'/error')
}
}
When I display the results it's done through the list method shown here.
def list(Integer max) {
List<Api> api = Api.findAllBySessionId(session.id, [sort:'dateCreated'])
api = api[-2..-1]
[apiInstanceList: api, apiInstanceTotal: api.size()]
}
So I have the unique session ID. How do I need to modify "mappings"?
Every domain object that you're saving will have an autogenerated ID (assuming you're using GORM, which is definitely likely). It sounds like all you're asking for is a /show/id page where you can access a particular object via ID.
A url mapping for "/$controller/$action?/$id?" is a pretty straightfoward way to handle this, and is provided by default (and used by scaffolded controllers also).
If you'd rather not use an autogenerated ID (maybe you're moving objects from one database to another, or updating the ID for some reason?) you can consider using java.util.UUID.randomUUID() to generate a random, unique identifier and save that as a field on your object. You could then use .findByUuid with the input parameter.

Zend Apigility : DELETE HTTP method Validation

I have recently explored Apigility I want to use HTTP DELETE method to delete some entity but before deleting I need to validate "entityId" must be given and must be Digit and trim.
Problem is documentation mentions that:
Content Validation currently only works for POST, PATCH, and PUT requests. If you need to validate query string parameters, you will need to write your own logic for those tasks.
https://apigility.org/documentation/content-validation/intro
I have make some custome modification in config file as bellow:
'NetworkingNightAPI\\V1\\Rpc\\DeleteSlotByLoginUser\\Controller' => [
'DELETE' => 'NetworkingNightAPI\\V1\\Rpc\\AssignTimeSlotToLoginUser\\Validator',
],
As I have mention DELETE method to validate same as NetworkingNightAPI\V1\Rpc\AssignTimeSlotToLoginUser\Validator but the issue is it always return 'Value could not be empty' even I have added valid row JSON values using PostMan
Thanks!
Thank you for your reply
What I have found is Apigility uses 'zf-content-validation' module for validating the input data (https://github.com/zfcampus/zf-content-validation)
This module dose not restrict such HTTP Methods you can apply validation to DELETE method as well Like it says that
"In the above example, the Application\Controller\HelloWorld\Validator service will be selected for PATCH, PUT, or DELETE requests, while the Application\Controller\HelloWorld\CreationValidatorwill be selected for POST requests."
So you just need to add manual entry for DELETE method in config file as below:
'NetworkingNightAPI\\V1\\Rpc\\DeleteSlotByLoginUser\\Controller' => [
'input_filter' => 'NetworkingNightAPI\\V1\\Rpc\\DeleteSlotByLoginUser\\Validator',
'DELETE' => 'NetworkingNightAPI\\V1\\Rpc\\DeleteSlotByLoginUser\\Validator',
],
In addition HTTP DELETE method will not validate using JSON row body from POSTMAN you have to pass query parameters and in your controller you need to get validated data using plugin like below:
$recruiterId = $this->getInputFilter()->getValues()['recruiterId'];
$timeSlotId = $this->getInputFilter()->getValues()['timeSlotId'];
If you want to delete a resource your should use the url that includes the route to that entity. This means the id would be in your route parameters, not in your query parameters. So the id is a route parameter/identifier and the RestController will search your entity using the identifier in the fetch($id) method of your resource listener. The listener should return a not found (404) response in case the entity with that identifier doesn't exist.
The content validation you mention in your question is for validating POST/GET parameters. So there is no need for such validator in case of a delete request.
So say for example you want to delete a Slot you would have a route:
api/v1/slots/[slot_id]
And if you want to delete Slot with id 1 you would send a delete request to:
DELETE
api/v1/slots/1
Your listener should simply return a 404 response in case a Slot with slot_id 1 doesn't exist.
I see you're using RPC Rather than Rest style - if you're passing the parameter using the query string you will have to validate it yourself inside the controller, for example:
public function someActionMethod()
{
$id = $this->getRequest()->getQuery('id');
$validator = new Input('id');
$validator->getValidatorChain()
->attach(new \Zend\Validator\NotEmpty())
;
$validator->getFilterChain()
->attach(new StringToUpper())
;
$inputFilter = new InputFilter();
$inputFilter
->add($validator)
->setData($this->getRequest()->getQuery())
;
if( ! $inputFilter->isValid()) {
return new \ZF\ApiProblem\ApiProblemResponse(
new ApiProblem(400, $inputFilter)
);
}
}
Apigility won't use any of the config generated using the UI to validate those fields for you wuen passed via query string as it says in the docs - they will be ignored. You would need to generate the valaidator yourself.
You could set it up to generate the validation using a config if you wished and then load the validator inside the controller to save writing boiler plate code as above.

Retain Sorting After Specific Action - Grails

I have a gsp form which displays the list of employees with the details (ie., Employee Name,Designation,Department,Status). All these columns are sortable. After calling a specific action in my controller class (ie., Changing the status of the employee from active to inactive and vice versa) the sorting gets disturbed. I am using the following code to sort while retrieving from DB
String strSort = params.sort ?: "empId";
strSort += " "
strSort += params.order?: "asc";
Is there any way I can retain the sort order which was there before posting a "Status change" action? If it is how it can be achieved?
As suggested by rvargas, it is possible through a variety of methods. queuekit plugin isn't released properly as yet so you could clone grails 3 / grails2 branch depending on which it is you are working with and also clone the test site to go with it to mess with this concept within the plugin:
In short You need to separate out your search feature and you can do this via a session value or send it as a subset list iteration.
I decided to not use sessions. Then when I click delete The bean is bound back in with the request sent (which be the id to delete)
At the very end it relists so no need to do any other here:
The most important bit being when I call the ajax reloadPage or even further postAction used by delete function is that I serialize search form. The actual search object is kept in a tidy manner here
But if this is too complex then in the very controller link the session search was commented out. I think you could just enable that forget all this complication and have a searchAgain() feature which renders the _list template like it does if it is xhr in my controller and rather than binding bean it binds the session.search map instead and if you did go down this route you probably want to change from g:render to g:include action="searchAgain"
Hope that helps you understand better
I can think of two ways to do it:
Pass your sort and order parameters to your action and send them back
with the result.
Store in session both parameters every time you update them.
To store and retrive from session use something like this:
private DEFAULT_SORT = 'myDefaultSort'
def myAction() {
if (params.sort && params.sort != session.getAttribute('sort-' + actionName)) {
session.setAttribute('sort-' + actionName, params.sort)
}
params.sort = session.getAttribute('sort-' + actionName)?:DEFAULT_SORT
...
//Your existing logic
}
If you receive a new/different sort parameter you save it into session. Then you try to load existing parameter from session, if you dont have any value stored, you get a default value.

Reusing json/model object to avoid making extra calls to controller

I've got a groovy userController and a _listMyUsers.gsp.
The _listMyUsers.gsp is using a
<g:dojoRemoteForm
formName="userSearchForm"
id="userSearchForm"
url="[controller:'user',action:'search']"
update="[success:'content']">
The method in the userController (search) is a simple criteria builder which returns the following back to the gsp, You can use controls in the gsp to customize the search criteria parameters (passed to the controller as param.field_name):
render (template:"listUsers",
model:[
users:users,
userTypes:UserTypeLookup.list(),
sortby:params.sortby,
direction:nextDirection,
currentDirection:sortDirection,
pager:pager,
organizations:orgs,
userType:userSearchTypes
])
Now this all works great and the model is then used to build out my usersList table. My problem comes in when I click on one of the users in the results to edit said users data, I then save. The save completes and returns to the main listUsers table. But it re-runs the search method with all searchCriteria wild carded as 'ALL' in the selections (so all users in the DB are returned).
My question is, how can I preserve the initial "custom" search returned so that when I get done editing my user, the original "search" is still there so my UI users don't have to go back and re-do their userSearch criteria again?
Thanks,
The Grails Cache Plugin might help you here. You could cache the output form the search action, using the user's query parameters as method arguments (so they can be used as keys to the cache).
#Cacheable('searchResults')
def search(String sortBy, String sortDirection /* other parameters */) {
// render the output
}
Then in your save action, you can use the CacheEvict annotation to clear the searchResults cache, so the search action will return the latest data:
#CacheEvict(value='searchResults', allEntries=true)
def saveUser() {
//save the user and return a response code
}
See the plugin documentation for details on specifying which items in the cache to evict, etc.

Laravel eager loading not returning data

Scenario:
An alert belongs to 1 user and 1 location, both referenced, respectively, by foreign keys in the alert table - user_id and location_id. The user_id will be the same for each request, but the location_id most definitely differs.
I want to display all alerts relating to that one user, I have successfully achieved this but without the use of eager loading.
my getIndex function so far:
public function getIndex()
{
$alert = User::with('alerts.location')
->where('id', '=', Auth::user()->id)->first();
$this->layout->content = View::make('agents.index',
array('alert' => $alert));
}
Printing the MYSQL query seems logically correct however, I am struggling to show the 'locations' part of the query.
My foreach loop is:
#foreach($alert->locations as $alert)
<td>{{ $alert->location->address_1}}</td>
#endforeach
However, it returns the error:
Invalid argument supplied for foreach()
Thank you for your help.
By accessing the data using this forloop, I was able to resolve the problem #foreach($alert->alerts as $alert).

Resources