How do you query a child and parent in laravel eloquent - php

I want to figure out how to query to get a result that was either created by the current user or the current users parent.
I have two tables users and workouts. Both tables have a created_by column, which stores the user id of whoever created said user or workout record.
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`created_by` int(10) unsigned DEFAULT NULL,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `users_created_by_foreign` (`created_by`),
CONSTRAINT `users_created_by_foreign` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`)
);
CREATE TABLE `workouts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`created_by` int(10) unsigned NOT NULL,
`description` text COLLATE utf8_unicode_ci,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `workouts_created_by_foreign` (`created_by`),
CONSTRAINT `workouts_created_by_foreign` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`)
);
In my user model I have a function to return all the workouts that the user has created.
public function createdWorkouts(): HasMany
{
return $this->hasMany(Workout::class, 'created_by');
}
What I want to figure out is, how can I query to find a workout using a ID but only for workouts the current user has created or the creator of the current user has created. Below is my current route logic, which only returns a workout created by the current user.
$user = User::find(1); // This would come from the JWT
if (!$workout = $user->createdWorkouts()->find($args[‘workout_id’])) {
return $response->withJson([], 404);
}

For this instance, I probably wouldn't use an eloquent relationship as it could be either the users id or their created_by value.
Instead, I would change the method on your user model to read:
public function createdWorkouts()
{
return Workout::where('created_by', $this->id)->orWhere('created_by', $this->created_by)->get();
}
Then you can do $user->createdWorkouts() which will return you a collection of all workouts where it was created by the user, or created by the user that created the user.
As it is a collection, you then have access to all of the other methods on a collection such as find etc

Related

How to access to sub related model when the related model returns a collection

I have 3 models: User, Payment and Log. A User has many Payment and both User and Payment have many Log.
User Model
class User
{
public function payments()
{
return $this->hasMany('Payment', 'user_id');
}
public function logs()
{
return $this->morphMany(Log::class, 'loggable');
}
}
users table
CREATE TABLE `users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Payment Model
class Payment
{
public function user()
{
return $this->belongsTo('User', 'user_id');
}
public function logs()
{
return $this->morphMany(Log::class, 'loggable');
}
}
payments table
CREATE TABLE `payments` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`status` varchar(50),
`amount` int(11) NOT NULL,
`collection_date` date NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`user_id` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_payments_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Log Model
class Log
{
public function loggable()
{
return $this->morphTo();
}
}
logs table
CREATE TABLE `logs` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`loggable_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`loggable_id` bigint(20) unsigned NOT NULL,
`old_values` text COLLATE utf8mb4_unicode_ci,
`new_values` text COLLATE utf8mb4_unicode_ci,
`user_id` bigint(20) unsigned DEFAULT NULL, /* the user that made the change, if any */
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
The Log model stores all changes made to any other model (it's a polymorphic relationship), so if the user changes its name, the Log model will store the older name and the new name. The same applies to Payment: if a payment status changes the Log model will have a new record with the old status and the new status.
I need to show a paginated list of all Log records for a specific User ordered by date. So my code is:
$user = App\User::find($id);
$allLogs = $user->logs();
// Now I need to join (I'm using union) both sets of logs
$allLogs->union($user->payments->logs());
However, since a User can have many Payment, $user->payments returns a Collection, so is no longer a query builder/eloquent object and it fails when I try to call ->logs().
$user->payments()->logs() also doesn't work, because $user->payments() returns a HasMany object and the ->logs() method doesn't exist.
I'm trying to avoid getting each collection of Log separately and then processing them using php (it would be perfect to delegate that task to MySql).
I believe it can be done, because I can write the query on MySql:
select l.*
from payments p
join logs l on p.id = l.loggable_id and l.loggable_type = 'App\\Payments'
where p.user_id = SOMEUSERID
Thanks in advance
Eager load the relations(reduces number of queries)
$user = User::with(['payments.logs', 'logs'])->find($id);
Query using the Log model.
$logs = Log::where([
'loggable_id' => $user->id,
'loggable_type' => 'User',
])
->orWhere(function($query){
$query->whereIn('loggable_id',
$user->payments()->pluck('id'))
->where('loggable_type', 'Payment');
})->get();
OR
Get them individually and then combine them.
$all_logs = collect([]);
$all_logs->push($user->logs);
foreach($user->payments as $p){
$all_logs->push($p->logs);
}
$final_logs = $all_logs->collapse();
OR
Just use the relations, without iterating over the payments. You can combine the results if you want(as shown in the previous approach).
$user_logs = $user->logs;
$payment_logs = $user->payments->pluck('logs')->collapse();

Laravel: Use model to return database row based on linked table.

I need to use my Website model to get a row from my database within the websites table, however this row is identified through my domains table.
So basically it would be great to do a query on my domains table and match the row, then from that get the website row from the websites table using the website_id column.
But I want to simply pass this data into my controller by just referencing the Model within the method.
class WebsiteController extends Controller {
public function index(Website $website) {
print_r($website);
return view('index');
}
}
My domains table:
CREATE TABLE `domains` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`website_id` INT(11) NOT NULL DEFAULT '0',
`domain` VARCHAR(255) NOT NULL DEFAULT '0',
`active` INT(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
INDEX `website_id` (`website_id`),
CONSTRAINT `website_id` FOREIGN KEY (`website_id`) REFERENCES `websites` (`id`)
)
COMMENT='This table will contain all of the domains registered on MarvWeb, this will link to the website record. '
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=3;
And websites table:
CREATE TABLE `websites` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NULL DEFAULT NULL,
`tagline` VARCHAR(255) NULL DEFAULT NULL,
`description` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COMMENT='This table will contain all the websites data. '
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2;
Does this make sense?
Add a website function to your Domain model.
class Domain extends Model{
public function website(){
return $this->hasOne('App\Website');
}
// remainder of model.
}
When you retrieve the Domain query results, the website can be accessed by
print_r($domainRowResult->$website->tagline);

ERROR 1005 (HY000): Can't create table 'db.POSTS' (errno: 150)

Hi I'm having issues creating my post database. I'm trying to make a forenge key to link to my users database. Can someone please help?
Here's the code for my tables :
CREATE TABLE USERS(
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (userID,UserName)
)ENGINE=InnoDB;
CREATE TABLE POSTS(
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthor varchar(255),
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(postAuthor) REFERENCES USERS(UserName)
)ENGINE=InnoDB;
Here's the last InnoDB error message:
Error in foreign key constraint of table db/POSTS:
FOREIGN KEY(postAuthor) REFERENCES USERS(UserName)
)ENGINE=InnoDB:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
There really should not be a good reason to have a compound primary key on the first table. So, I think you intend:
CREATE TABLE USERS (
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (userID),
UNIQUE (UserName)
);
CREATE TABLE POSTS (
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthor int,
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(postAuthor) REFERENCES USERS(UserId)
);
Some notes:
An auto-incremented id is unique on every row. It makes a good primary key.
A primary key can consist of multiple columns (called a composite primary key). However, an auto-incremented id doesn't make much sense as one of the columns. Just use such an id itself.
If you use a composite primary key, then the foreign key references need to include all columns.
I chose UserId for the foreign key reference. You could also use UserName (because it is unique).
UserName is a bad choice for foreign keys, because -- conceivably -- a user could change his or her name.
The error is caused by incorrect foreign key definition. In the concrete case you are missing a complete column in your foreign key definition.
In the USERS table you have defined primary key as composite key of UserID and UserName columns.
CREATE TABLE USERS (
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (UserID,UserName)
) ENGINE=InnoDB;
note that it is good practice to respect case of the identifiers (column names)
In the POSTS table you declared your foreign key to reference only one column in the USERS table, the UserName column. This is incorrect as you need to reference entire primary key of the USERS table which is (UserID, UserName). So to fix the error you need to add one additional column to the POSTS table and change your foreign key definition like this:
CREATE TABLE POSTS(
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
authorId int,
postAuthor varchar(255),
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(authorId, postAuthor) REFERENCES USERS(UserID, UserName)
) ENGINE=InnoDB;
Please look at following fiddle: http://sqlfiddle.com/#!9/92ff1/1
NOTE: If you can you should re-architect this to not use the composite primary key in the USERS table as it does not make sense from what I can see in the displayed code. You can change the tables like this:
CREATE TABLE USERS (
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (UserID)
) ENGINE=InnoDB;
CREATE TABLE POSTS (
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthorID int,
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(postAuthorID) REFERENCES USERS(UserID)
) ENGINE=InnoDB;;

Simple PHP/MySQL ACL System

I have a simple ACL system in PHP and MYSQL started. I need help finishing it though...
I have 2 Database tables shown below...
user_link_permissions : Holds a record for every user, on every entity/link that permissions apply to...
--
-- Table structure for table `user_link_permissions`
--
CREATE TABLE IF NOT EXISTS `user_link_permissions` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`user_id` int(30) NOT NULL,
`link_id` int(30) NOT NULL,
`permission` int(2) NOT NULL DEFAULT '0',
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2055 ;
intranet_links : Is basically the entity that the permission gives or revokes user access to
--
-- Table structure for table `intranet_links`
--
CREATE TABLE IF NOT EXISTS `intranet_links` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`description` text NOT NULL,
`url` varchar(255) DEFAULT NULL,
`notes` text,
`user_login` varchar(255) DEFAULT NULL,
`user_pw` varchar(255) DEFAULT NULL,
`active` int(2) NOT NULL DEFAULT '1',
`sort_order` int(11) DEFAULT NULL,
`parent` int(10) NOT NULL DEFAULT '1',
`local_route` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
UNIQUE KEY `local_route` (`local_route`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ;
To save these permissions settings I have a matrix style grid like this below where each checkbox is a record in the user_link_permissions table...
I need help creating a simple ACL function in PHP which can check if a user has permission or not to view a link/entity based on the database results.
On page load I am thinking I can query the user_link_permissions DB table for all records with a matching user ID of the logged in user and store them to a session array variable.
A function could then use that array to check for a link/entity permission using that array value on the entity key.
I just can't visualize how it might look at the moment in PHP.
Any help please?
function aclCanAccess($user_id, $entity_id){
}
$entity_id = 123;
if(aclCanAccess(1, $entity_id){
// yes user can see this item
}else{
// NO user permission denied
}
I will leave writing the code to you for fun.
Assume you are storing all the previously queried permissions in a variable called $_SESSION['acl']
Your ACL function should:
check the session if you already queried that entity
if it is not set, read it from the db
in short
function..... {
if(!isset($_SESSION['acl'][$entity_id])) {
$_SESSION['acl'][$entity_id] = query here to return to you if he has access or not
}
return $_SESSION['acl'][$entity_id];
}
You can also read the entire array when you log in the user. That might also be appropriate. In that case you should be able to just
return $_SESSION['acl'][$entity_id];
But I would then try and catch an exception in case it is not set.

How do I get rows based on another table with Eloquent?

I have one table with profiles. In this table there is no way to know what user have access to each row.
CREATE TABLE `rw_profiles` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
)
Then I have another table to link each user with a profile. This table can contain same profile_id but different user_id (many users can access same profile).
CREATE TABLE `rw_profile_access` (
`profile_id` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
UNIQUE KEY `profile_access_profile_id_owner_unique` (`profile_id`,`owner`),
KEY `profile_access_user_id_foreign` (`user_id`),
CONSTRAINT `profile_access_profile_id_foreign` FOREIGN KEY (`profile_id`) REFERENCES `rw_profiles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `profile_access_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `rw_users` (`id`)
)
How do I list all profiles that a user has access too? Are you supposed to use the with-method?
Something like $profiles = Profile::with('...')->get();?
Update
As of now I'm joining the table.
$profiles = Profile::join('profile_access', function($query) use ($user) {
$query
->on('profile_id', '=', 'profiles.id')
->on('user_id', '=', DB::raw($user['id']));
})->get(['profiles.*']);
That works. Is this the only way or can I do it without join?
You need to define the many-to-many relationship in your User and Profile models. They need methods like:
class User {
public function Profiles()
{
return $this->belongsToMany('Profile', 'rw_profile_access', 'user_id', 'profile_id');
}
}
class Profile {
public function Users()
{
return $this->belongsToMany('User', 'rw_profile_access', 'profile_id', 'user_id');
}
}
The parameters for Profiles() and Users() correspond to:
Related model
Pivot table
Foreign key
Foreign key
You can then query like this:
$users_with_their_profiles = User::with('profiles')->get();
$users_that_definitely_have_profiles = User::with('profiles')->has('profiles')->get();
The Laravel documentation explains this thoroughly at http://laravel.com/docs/eloquent#relationships.
You can use many to many relationship.
Laravel table relationship
http://laravel.com/docs/eloquent#working-with-pivot-tables
OR:
Assume you have ProfileAccess model.
$profiles = ProfileAccess::with('profile')
->where('user_id', $user['id'] )
->get();
foreach($profiles as $profile) {
dd($profile->profile->name);
}

Categories