Check if the user_id is exist inside query - php

I've tried to query using laravel eloquent where user is following a specific brand.
The problem: How to query listing of brand and let me know if current login user is following the brand?
got 3 tables:
Brand:
Id | name | logo
User:
Id | name | email | password
Followers:
brand_id | user_id
Now i tried to query all brand and inside of the collection i want to add
is_follow = 1 or is_follow = 0
if the user already follow or 0 if not exists.
I'm using fractal so maybe it can be easier to query. but i don't really get it how to query it out with check the user_id first.
Thanks
*Update
I manage to solve it. But i think its a bad practice.
$user_id = Request::get('user_id');
foreach($brands->followers as $value){
$array[] = $value->user_id;
}
if(in_array($user_id, $array)){
$is_follow = 1;
}

You can check if the authenticated User follows a specific Brand with:
$user = Auth::user();
$exists = $user->brands->contains($brand_id);
You can also do it with a raw query which will be better in terms of performance:
$exists = DB::table('user_brand')
->whereBrandId($brand_id)
->whereUserId(Auth::user()->id)
->count() > 0;

Related

Order by infos do not have approved or rejected yet

I have HR dashboard display all forms (The applicants form)
I want to display it order by pending forms
I wrote this code but it doesn't work
public function index(){
$pending = PersonalInfo::doesntHave('hraction')->first();
$infos = PersonalInfo::orderBy($pending, 'desc')->latest()->simplePaginate();
$rank = $infos->firstItem();
return view('HR/HrEmployee',["infos",$infos,"rank"=>$rank]);
}
And this error appeared
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.jpg","personlPhoto":"resources\/images\/$2y$10$XoxGRUQiFBZgroZfj0R5ef8LnSro...' at line 1 (SQL: select * from personal_infos` order by ... limit 16 offset 0)
To be clear for you i have tow tables (personalInfos & Hractions)
prsonalInfos:
| id | firstname | fathername | ...
Hractions:
| id | user_id | action | comment | personal_id | created_at |updated_at
your variable $pending is a whole collection, you can not pass it as is, you need a column name there instead.
$infos = PersonalInfo::orderBy('firstname', 'desc')->latest()->simplePaginate();
firstname is just an example, put the appropriate field of the table you want to order there.
So basically you don't need to use the same model 2 times, you can simply do:
$infos = PersonalInfo::doesntHave('hraction')->orderBy('firstname', 'desc')->latest()->simplePaginate();
This will return you all the data from PersonalInfo model without hraction relationship and use ordering + pagination on them in one step.
orderBy()'s first argument needs to be a field in the database.
If you want to order them from latest to most recent you can use either the id field, or created_at.
Something like this:
$infos = PersonalInfo::orderBy('id', 'desc')->latest()->simplePaginate();
$infos = PersonalInfo::orderBy('created_at', 'desc')->latest()->simplePaginate();
in the end the Eloquent model queries are being transformed into plain SQL. So if you had that in mind, it will be much simpler to build the eloquent queries.

User Record Ownership with OctoberCMS & MySQL

I'm using OctoberCMS based on Laravel, with the official User plugin.
I'm making a gallery where frontend users can upload files.
The user is the owner of their uploaded file and is the only one that has permission to edit.
My question, is this the correct way to design and handle user record ownership? All user upload records will be mixed together in one database table mysite_gallery_ and will be sorted and displayed in html with filters, such as viewing all uploads by a specific username.
Will this be slow? Should each user have their own table? Will it be secure enough to prevent another user, bot, or hack script from editing a file record they don't own?
MySQL Table
All upload records are saved to the table mysite_gallery_.
| id | username | filename | slug | title | tags |
| ---- | ---------- | ---------- | -------- | --------- | -------------------- |
| 1 | matt | xyz123 | xyz123 | My File | space, galaxy, stars |
Record Ownership
At upload, my custom Upload component uses Laravel to create a record in the database of the file's title, slug, tags, etc.
To define ownership I have the Upload component save the user's username to the record.
# Get Current User
$user = '';
if (Auth::check()) {
$user = Auth::getUser();
$user = $user->username;
}
# Create Record
$gallery = new Gallery();
$gallery->username = $user;
$gallery->filename = $name;
$gallery->title = $title;
$gallery->slug = $slug;
$gallery->tags = $tags;
$gallery->save();
Edit Record
If the user wants to edit the file properties, such as title, Laravel checks if current user matches the username in the record. If user is owner, it allows edit.
# Get File Record Owner
$owner = '';
if (Gallery::where('filename', '=', $filename)->exists()) {
$record = Gallery::where('filename', '=', $filename)->first();
$owner = $record->username;
}
# Authenticate Current User is Owner
$is_owner = false;
if (Auth::check()) {
# Get Current User
$user = Auth::getUser();
# Check if User is Owner
if ($user->username == $owner) {
$is_owner = true;
}
}
# Edit Record
if ($is_owner == true) {
# Update Record
Gallery::where('filename', '=', $filename)->update(['title' => $title]);
return Redirect::back();
}
It is a better idea to use the users id instead of the username. It'll take less space in the database and is also faster.
Also I would put the tags in another table. Although this depends on how you use the tags. If you have them in another table then it would be easier to get all the uploads for a tag for example.

pending timesheet check function with 2 queries not working

I'm trying to get this pendingsubmission function to work properly. The way its suppose to work is if a manager logs into his account and has pending timesheets to review i want somekind of notification to the manager that there are pending timesheets.
Here is my code so far although it only works for the first result (first timesheet, does not get manager for all other timesheets submitted) i apologize if this is confusing.
function pendingsubmissions($loggedInUser) {
include("table_names.inc");
global $authenticationManager;
list($qh, $num) = dbQuery("SELECT uid FROM $TIMES_TABLE WHERE submitstatus=1 OR ot_status=1");
while ($data = dbResult($qh)) {
$username = $data['uid'];
list($qh2,$num2) = dbQuery("SELECT manager FROM $USER_TABLE WHERE username='$username'");
while ($data2 = dbResult($qh2)) {
$manager = $data2['manager'];
if ($loggedInUser == $manager || $authenticationManager->hasClearance(CLEARANCE_ADMINISTRATOR))
return 1;
else
return 0;
}
}
}
The first query is to check the database for timesheets that are pending (submit status 1).. if there are any found then the second query is to find out that users manager and then if that users manager is currently logged in, spit out the true value.
The problem is the first query as of now it is showing as follows:
uid
---
user1
user1
user1
user2
user2
user2
and the second query is only checking for user1 manager name.. doesnt check user2.. can someone help fix this so it checks every user for manager-name
thanks
As already mentioned, you can use DISTINCT, or GROUP BY a value such as uid.
This could also be achieved with a single query. Something like:
SELECT manager FROM $USER_TABLE WHERE username IN (SELECT DISTINCT uid FROM $TIMES_TABLE WHERE submitstatus=1 OR ot_status=1)
This saves you sending two requests to the database.
You're also overwriting your values each time, instead of:
while ($data = dbResult($qh)) {
$username = $data['uid'];
You will want to do something like:
$usernames = array();
while ($data = dbResult($qh)) {
$usernames[] = $data['uid'];
You should write a single query with a JOIN between the 2 tables. At present you are only asking the second query to look for one value!
Also, punctuation is as important in English as it is in programming. Please use apostrophes where they are required. It makes reading your question much easier.

create tree through recursive function

I have a table
id,name,parent_id,designation columns,
i want create tree through recursive function in php.
every parent_id is looking in id column and if user login then user can see own and all below records according parent_id.
like
A
|
B
|
c
|
D
|
E
|
F
if A user login then he can all(A,B,C,D,E,F) details.and if B login then see (B,c,D,E,F) and like all... if F login then he can see only own records..
Thanks for advance
create a function fetch_parent;
function fetch_parent($parent_id) {
$query = 'SELECT * FROM `my_table` WHERE `parent_id`='. $parent_id;
// use your own sql class/function whatever to retrieve the record and store it in variable $parent
if($parent->parent_id !== null) { // asuming a 'root' record will have null as it's parent id
fetch_parent($parent->parent_id); // here you go with your recursion
}
return;
}
Then just call the function with the record you want it's parents from:
$first_parent_id = 8;
fetch_parent($first_parent_id);
Notes:
the $parent var can also be an array, depending on the mysql result set
PLEASE PLEASE PLEASE check $parent_id in the query for mysql injection etc.

How to update a table column based on it's relation to another table?

I have a table called "profiles". There was a column in this table called "user_id" which I have changed the name to "username" and the type from INT(11) to Varchar(255) . However the contents of this column are still numeric ids.
These ids correspond to another table called "users". That table has fields called "user_id" and "username". For each row on the "profiles" table I need to first check to see what the username field has for the id and do a look up on the users table to get the username that correcponds to that id and then update the profile table's username value for with the proper username.
Profiles table:
username | blah blah...
------------------------
1 | ...
Users table:
user_id | username
------------------------
1 | Joe
I need the value for the username field on the profiles table to be updated to "Joe".
I came up with this php script but it stops working after updating just 4 records for some reason:
$sql = 'SELECT username FROM profiles';
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)) {
$id = $row['username'];
$sql = 'SELECT username FROM users WHERE user_id = '. $id;
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)) {
$sql = "UPDATE profiles SET username = '".$row['username']."' WHERE username = $id";
$query = mysql_query($sql);
if(!$query) {
echo 'error!';
}
}
}
My script isn't all that efficient to begin with, although that's not that big an issue since the table has just 50k records. Anyway what would be a way to do this directly from mysql?
You are manipulating the $row variable inside the first loop. Obviously it does not work. Try giving the variable in inner loop a different name.
And not only that almost all the variables you are using, outside the first loop, you are using the same names inside the inner loop.
Also coming to db schema I would prefer ids to be foreign keys not usernames because querying using ids would be faster than with columns of type varchar.
One more suggestion is that there is no need to use
while($row = mysql_fetch_assoc($query))
because there would be only one row
As Napster said you're overwriting your $query, and $row variables. That should fix your immediate issue.
Additionally, a query inside of a while loop, inside of a while loop is absolutely terrible. No offense intended! We all have to start somewhere. But I would strongly look into how you can rewrite this with a JOIN just so you have something in your toolbelt for that next time.
Hope that helps!
I think relationship between your tables is wrong, you should have a foreign key in profiles table that links to user_id in the users table, then if you change something like Joe to Michael, its corresponding record in profiles table will be updated.
Profiles table:
user_id | blah blah...
------------------------
1 | ...
Users table:
user_id | username
------------------------
1 | Joe
You can do this in one query
UPDATE profiles t1
INNER JOIN users t2 ON t1.username=t2.user_id
SET t1.username=t2.username
Why you would want to do this is another question.

Categories