User::where returns null collection - php

I am trying to build a profile section of my website where I can take the username from the URL and query my database for that username. Either the other questions I have read are out of date or I am doing something wrong. I run the following Eloquent command in php artisan tinker
App\User::where('name', 'Tom');
However, when I run this command in my terminal, I get a blank eloquent collectioion. I am confused. Here is where I got my information for the where query: Find User in Laravel by Username

As far as I can see in documentation (https://laravel.com/docs/5.3/queries) to return an actual row you need to use the first method, or to return several rows the get method.
This code would return the first instance of name='Tom':
App\User::where('name', 'Tom')->first();
If you're trying to get all the rows equal to Tom, then you would do this:
App\User::where('name', 'Tom')->get();

Related

Symfony / Doctrine - Get a result based on a json column

I'm using Symfony 6.1, doctrine/orm 2.12.3 and PostgreSQL. Trying to write functional tests, I need to login a user with a ROLE_ADMIN (I used the security bundle as well).
From what I have seen on Symfony Docs, since 5.1 you can log in a user with the loginUser() method, but you can't specify roles or anything. Based on that, I tried to retrieve a user with a custom query in my UserRepository.
I tried using DQL but id doesn't work at all with json, it can't compare the json with the query. The following query always returns null.
public function findOneByRoleAdmin()
{
$rsm = $this->createResultSetMappingBuilder('u');
$sql = $this->getEntityManager()->createNativeQuery('SELECT * FROM public."user" AS u WHERE u.roles::text LIKE \'%ROLE_ADMIN%\' ORDER BY u.id LIMIT 1', $rsm);
return $sql->getOneOrNullResult();
}
Using $sql->getResult() instead of $sql->getOneOrNullResult() returns an empty array.
I know I have data in my test database because dumping a simple findOneBy() shows me the last user created. I also know that the query is valid because it works on the PGAdmin query editor.
I can't figure out why I can't retrieve a user with this, and I don't even know if my workaround is a good one.

Get a user with posts

I am trying to get a user with his posts in laravel, so far I have tried to use the following line
User::findOrFail($user_id)->with('posts')->first();
But I am getting the first user on the table regardless of what the user ID specified is.
I have tried to dd the user_id and it's working fine, (getting the user_id from the route).
So far the result I am getting is if the user id is x and the first user in the table has an id of 1 I get the info of user id 1 and his posts.
Thanks in advance!
You have your methods in the wrong order.
findOrFail executes the query immediately, which returns the User record for $user_id.
Chaining that to ->with() will start a new query.
Finally, calling ->first() returns the first User from the database.
Adjust your query as such:
User::with('posts')->findOrFail($user_id);
findOrFailand first will give you the User Object but you have to decide witch function you will use.
If you use Routemodel Binding then you can use:
User::with('posts')->first(); or User::load('posts');
If you dont use routemodel Binding you can use findOrFail like that:
User::with('posts')->findOrFail($user_id);

How to use laravel Eloquent to take just one field?

I am new in Laravel and I am watching a video tutorial that is teaching Laravel 3, unfortunately Laravel 4 is very different with laravel 3 and I don't know why? and I am afraid that maybe laravel 5 will be so different with laravel 4.
I am going to select all data about one field from my users table:
$user=new user;
$username=$user::find(1)->username;
return $username;
The top code is working true but just return the username of a user that it's id is equal to 1, But I want to do something like below:
$user=new user;
$username=$user::all()->username;
return $username;
This code has error $user::all()->username; and the error is :
Undefined property: Illuminate\Database\Eloquent\Collection::$username
You can use the lists() function, described here
It will return an array with all the values of one property.
(Also you don't need to create an instance to retrieve all users)
$usernames = User::lists('username');
If you'd like to have another column as key of your array (e.g. the id) do this:
$usernames = User::lists('username', 'id');
Don't be worried about Laravel 5. Some things will change but many things will stay the same. Including everything about Eloquent and the DB querying in general (at least as far as I know)

Laravel - Execute function before query is fired

is there a way for Eloquent/raw queries to execute a function before a query is fired? It would also be nice if I could extend the functionality to pass a parameter if the function should be run before or not. Depending on the outcome of the function (true/false) the query shouldn't be executed.
I would be nice to use the principal of "DB::listen", but I'm not sure if I can stop or run the query from within this function.
The reason for this is that I would like to build a little data warehouse myself for permanently saving results to a warehouse (db) and not query a huge database all the time.
The method I'm would like to use is to create a hash of a query, check if the hash exists in the warehouse. If it exists, then the value is returned. If not the query is executed and the output is saved together with the hash into the warehouse.
Any ideas?
///// EDIT /////
I should clarify, that I would like to access the queries and update the value if the calculated value needs to be updated. i.e.: Number of cars in december: While I'm in december, I need to keep updating the value every so often. So I store the executed query in the db and just retrieve it, run it and then update the value.
//// EDIT 2 /////
Github: https://github.com/khwerhahn/datawarehouselibrary/blob/master/DataWareHouseLib.php
What I would like to achieve is to hook into Laravels query/Eloquent logic and use the data warehouse logic in the background.
Maybe something like this:
$invalid_until = '2014-12-31 23:59:59'; // date until query needs to be updated every ten minutes
$cars = Cars::where('sales_month', '=', 12)->dw($invalid_until)->get();
If the dw($date_parameter) is added I would like Laravel to execute the data warehouse logic in the background and if found in the db then not execute the query again.
You don't need to use events to accomplish this. From the 4.2 docs:
Caching Queries
You may easily cache the results of a query using the remember method:
$users = DB::table('users')->remember(10)->get();
In this example, the results of the query will be cached for ten
minutes. While the results are cached, the query will not be run
against the database, and the results will be loaded from the default
cache driver specified for your application.
http://laravel.com/docs/4.2/queries#caching-queries
You can also use this for Eloquent objects,
eg: User::where($condition)->remember(60)->get()
I get what you're trying to do, but as I view it (I might not still be getting it right, though) you still can get away with using rememberForever() (if you don't want a specific time limit)
So, let's pretend you have a Cars table.
$cars = Cars::where('sales_month', '=', 12)->rememberForever()->get();
To work around the problem of deleting the cache, you can assign a key to the caching method, and then retrievit by that key. Now, the above query becomes:
$cars = Cars::where('sales_month', '=', 12)->rememberForever('cars')->get();
Every time you run that query you will be getting the same results, first time from the DB, all the others from the cache.
Now you say you're going to update the table, and you want to reset the cache, right?
So, run your update, then forget() the Cache with the cars index:
// Update query
Cache::forget('cars');
Your next call to the Cars query will issue a new resultset, and it will be cached. In case you're wondering, the remember() and rememberForever() are methods of the QueryBuilder class that use the same Cache class you can see in the docs in its own section.
Alternatively, in fact, you could also use the Cache class directly (it gives you a better control):
if (null == $cars= Cache::get('cars')) {
$cars = Cars::where('sales_month', '=', 12)->get();
Cache::forever('cars', $cars);
}
By overriding the method runSelect exsists in Illuminate\Database\Query\Builder that runs in every select query in Laravel.
see this package:
https://github.com/TheGeekyM/caching-queries

Get the last insert id

Hello I am using cakePHP 1.3 and I am unable to retreive the last inserted row's id. I actually am using $this->Model->id to retreive the last inserted id but I am unable to get the id. When tried to check what is return type, it says as bool(false), which means nothing is returned.
Here I am loading a different model in a different controller, so would that be the issue?? But even though I am loading, I get back nothing!!
$this->loadModel('Contact');
$this->Contact->query("insert into contacts(tblContact_firstName,tblContact_lastName,tblContact_company,tblContact_department,tblContact_address,tblContact_country,tblContact_city,tblContact_state,tblContact_zipcode,tblContact_phone1,tblContact_email1) values('$sanitizedFormData[fname]','$sanitizedFormData[lname]','','$sanitizedFormData[company]','$sanitizedFormData[address]','$sanitizedFormData[country]','$sanitizedFormData[city]','$sanitizedFormData[state]','$sanitizedFormData[zip]','$sanitizedFormData[phone]','$sanitizedFormData[email]');");
$this->loadModel('Contact');
$contactId = $this->Contact->id;
And when I printed the $this->Contact array recursively, I found the value of "id" key empty. So that explains why I was receiving an empty value.
Now given my situation, how would I get the last inserted id, specific to the controller Contact?
I think you just want to do:
$this->getLastInsertID();
http://book.cakephp.org/2.0/en/models/additional-methods-and-properties.html#model-getlastinsertid
When you use query() you loose a lot of automagic cakephp provides. Use save() instead.
In fact, you even do not need to load Contact in this case. You can execute any query from the current controller with query() even saving to any other table.
You can also avoid using loadModel() if your current model is somehow associated with Contact ($this->CurrentModel->AnotherOne->Contact->save(...)).
If this is MySQl you could use "SELECT from contacts LAST_INSERT_ID()" query to get last ID.
or just "SELECT LAST_INSERT_ID()"
For MSSQL it is "SELECT ##IDENTITY".
This bypasses any solution in cakePHP though, so there might be a better solution.
You can get last inserted record id by
echo $this->ModelName->getLastInsertID();
Alternately, you can use:
echo $this->ModelName->getInsertID();
This methods can be found in cake/libs/model/model.php on line 2775
Note: This function doesn't work if you run the insert query manually

Categories