I'm trying to easily check if a given user_id is a friend of the current user so I can simply do a check within a blade #if statement. My friendship functionality is two-way, and accepting a friendship is not required.
I have seem to have some setup going, but am not confident that I'm doing it properly.
Friendship Table
Schema::create('friendshipLinks', function ($table) {
$table->increments('id');
$table->integer('userId_1'); // foreign key
$table->integer('userId_2'); // foreign key
$table->timestamps();
$table->foreign('userId_1')->references('id')->on('users')->onDelete('cascade');
$table->foreign('userId_2')->references('id')->on('users')->onDelete('cascade');
});
User Model (Trimmed)
class User extends Eloquent implements UserInterface, RemindableInterface {
use EloquentTrait, UserTrait, RemindableTrait;
protected $table = 'users';
// RELATIONSHIPS
public function posts() {
return $this->hasMany('Post');
}
// FRIENDSHIP
function friends() {
return $this->belongsToMany('User', 'friendshipLinks', 'userId_1', 'userId_2');
}
function friendsWith() {
return $this->belongsToMany('User', 'friendshipLinks', 'userId_2', 'userId_1');
}
}
Friendship Model
class Friendship extends Eloquent {
protected $table = 'friendshipLinks';
protected $fillable = ['userId_1', 'userId_2'];
}
At the moment I can get an array of all the users friends with (Two-way)
$friends = User::find($id)->friends;
$friendsWith = User::find(Auth::user()->id)->friendsWith;
$result = $friends->merge($friendsWith);
How can I easily implement something that will allow me to call a function that return a boolean like:
$isFriend = User::find($id)->isFriend($friend_id);
Here is the solution method in user model's class:
public function isFriend($friendId) {
return (boolean) $this->friends()->where('users.id', $friendId)->count();
}
Related
I have a scenario where User has a belongsToMany relation with PortalBreakdown, PortalBreakdown has a belongsTo relation with Portal. Portal has order column in it. I have a method listing_quota($id) in UserController which returns all breakdowns of the user. I want to sort these breakdowns based on order column of the portal. Below are the code of classes and a method I have tried.
class User extends Model {
protected $table = 'user';
public function listing_quota() {
return $this->belongsToMany('App\PortalBreakdown', 'user_listing_quota')->withPivot(['quota']);
}
}
class PortalBreakdown extends Model {
protected $table = 'portal_breakdown';
public function portal() {
return $this->belongsTo('App\Portal');
}
}
class Portal extends Model {
protected $table = "portal";
protected $fillable = ['name', 'description', 'order'];
}
Below is the method where I am trying to return sorted by order. I tried few things some of which can be seen in commented code but not working.
class UserController extends Controller {
public function listing_quota($id)
{
$user = User::with(['listing_quota' => function ($query) use ($id) {
// $query->sortBy(function ($query) {
// return $query->portal->order;
// });
}, 'listing_quota.portal:id,name,order'])->findOrFail($id);
// $user = User::with(['listing_quota.portal' => function ($q) {
// $q->select(['id', 'name',order']);
// $q->orderBy('order');
// }])->findOrFail($id);
return $this->success($user->listing_quota);
}
}
I also tried chaining orderBy directly after relation in Model class but that's also not working from me. Thank you in advance.
NOTE: I am using Laravel Framework Lumen (5.7.8) (Laravel Components 5.7.*)
I'am beginner in Laravel. I have project in Laravel 5.8.
I have User model:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
use psCMS\Presenters\UserPresenter;
use scopeActiveTrait;
public static $roles = [];
public $dates = ['last_activity'];
// ...
public function scopeHistory()
{
return $this->hasMany('App\UserLoginHistory');
}
// ...
}
and UserLoginHistory:
class UserLoginHistory extends Model
{
protected $quarded = ['id'];
public $timestamps = false;
protected $fillable = ['user_id', 'date_time', 'ip'];
public function user()
{
return $this->belongsTo('App\User');
}
}
I want show user login history by this code:
User::history()->where('id', $idAdmin)->orderBy('id', 'desc')->paginate(25);
but it's not working.
This function not working - I haven't got results.
How can I fixed it?
First of all, you are defining your relationship as a scope (prefixing the relationship with the scope keyword). Try updating your model relationship to this:
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
Then, given your query, it seems that you want to get all the UserLoginHistory
records for a given User. You could accomplish this in two ways (at least).
From the UserLoginHistory model itself, constraining the query by the foreign key value:
$userId = auth()->id(); // get the user ID here.
$results = UserLoginHistory::where('user_id', $userId)->paginate(15);
// ^^^^^^^ your FK column name
From the User model using your defined relationship:
$userId = auth()->id(); // get the user ID here.
$results = User::find($userId)->history;
The downside of the second approach is that you'll need to paginate the results manually.
in your User model you should define your relation by this way :
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
then if you would like to select with history model you can do that with WhereHas() method :
User::whereHas(['history'=>function($q) use ($idAdmin) {
$q->where('id',$idAdmin)
}])->orderBy('id', 'desc')->paginate(25);
You must be do this changes
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
usage
$user = User::find($idAdmin);
$userHistories = $user->history()->latest()->paginate(25);
or get user with all history
User::with('history')->find($idAdmin);
// Post model
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
}
// Category model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
}
I use eloquent with soft delete .I'm getting error because of my query still select data that already use softdelete here is my model
User Model
class User extends Authenticatable
{
use Notifiable, HasRoles, SoftDeletes;
protected $guard_name = 'web';
protected $fillable = [
'username', 'password'
];
protected $dates = ['deleted_at'];
}
for example I've 100 user and I deleted 1 user with softdelete . then I try to
$a = User::all();
dd($a);
I get 99 user . It works! but after I use it relation It doest work here what I do
This is my Parent table and Model
table
|id|user_id|parent_id|
Note : user_id and parent_id are FK in user.id table
class Parent extends Model
{
protected $table = 'parent';
public function user()
{
return $this->belongsTo('App\User');
}
}
$getParent = Parent::with('user')->get();
when I dd($getParent); why I still get null data from user_id that I already use soft deleted ?
UPDATE model User : after I put whereNull I still getting user that I alredy soft deleted
public function user()
{
return $this->belongsTo('App\User')->whereNull('users.deleted_at');
}
https://laravel.com/docs/5.7/eloquent#querying-soft-deleted-models
...
public function customerAddress()
{
return $this->hasOne(Addresses::class, "id", "id_address")->withTrashed();
}
...
Ok, here's what I think is going on...
With soft delete the ondelete event doesn't work (meaning that related models is not deleted). I'm not sure if that changed in later versions of Laravel, but I don't think so. Also deleting User would still not affect the parent model, since you haven't defined the relationship between User and Parent (in the User model), only between Parent and User.
Try defining the relationship in User and then override the boot() function, that sits in the Model class. (This is untested code, but something like this should do the job)
class User extends Authenticatable
{
use Notifiable, HasRoles, SoftDeletes;
protected $guard_name = 'web';
protected $fillable = [
'username', 'password'
];
protected $dates = ['deleted_at'];
// Override Model boot function
protected static function boot()
{
parent::boot();
static::deleting(function ($users) {
foreach ($users->parents()->get() as $parent) {
$parent->delete();
}
});
}
// Define relationship with parent model
public function parents()
{
$this->hasMany('App\Parent');
}
}
You can put a constraint on the Eager Load:
public function groups()
{
return $this
->belongsToMany('Group')
->whereNull('group_user.deleted_at') // Table `group_user` has column `deleted_at`
->withTimestamps(); // Table `group_user` has columns: `created_at`, `updated_at`
}
Instead of HARD deleting the relationship using:
User::find(1)->groups()->detach();
You should use something like this to SOFT delete instead:
DB::table('group_user')
->where('user_id', $user_id)
->where('group_id', $group_id)
->update(array('deleted_at' => DB::raw('NOW()')));
I am struggling with this for a while now, but I can't figure it out how it works.
In laravel I have a few models with relationships. I wan't to have al the accounts based on the logged in user and the passed parameter for the workspace.
This is how the models looks like: (I only coppied the methods to keep it short)
The user Model:
class User extends Eloquent implements UserInterface, RemindableInterface {
public function workspaces()
{
return $this->hasMany('Workspace', 'user_id');
}
public function account()
{
return $this->hasManyThrough('account', 'Workspace', 'id', 'workspace_id');
}
}
The workspace model:
class Workspace extends Eloquent implements UserInterface, RemindableInterface {
public function account()
{
return $this->hasMany('account', 'workspace_id', 'id');
}
public function user()
{
return $this->belongsTo('User', 'user_id', 'id');
}
}
The account model
class account extends Eloquent implements UserInterface, RemindableInterface {
public function account_url()
{
return $this->hasOne('acountUrl', 'id', 'account_url_id');
}
public function workspace()
{
return $this->belongsTo('Workspace', 'workspace_id', 'id');
}
}
The account_url model
class account_url extends \Eloquent implements UserInterface, RemindableInterface {
public function account()
{
return $this->belongsToMany('account', 'id', 'account_url_id');
}
}
So I want from the logged-in user with a specific workspace all the account with the account_urls
something like this: user->workspace->account->account_url
I tried the following things but it don't work:
$account_urls = user::find( Auth::user()->id)->first()->workspaces()->where('id', '=', 1)->account()->account_url()->select('url')->get();
and:
$account_urls = account::where('workspace_id', '=', '1')->account_url()->select('url')->get();
Only when I do it like this:
$account_urls = account::find(1)->account_url()->select('url')->get();
But then I get only 1 url, but when I replase find(1) for all() I get an error?
Is there someone who can help me with this?
Tanks,
Your relations are wrong, change them to:
// User
public function account()
{
return $this->hasManyThrough('Account', 'Workspace', 'user_id', 'workspace_id');
}
// Account
// use camelCase for relations
public function accountUrl()
{
// I assume you have account_url_id on accounts table
// If it's opposite, then use hasOne
return $this->belongsTo('AcountUrl', 'account_url_id', 'id');
}
// AccountUrl (use camelCase)
public function account()
{
// if above is hasOne, then here belongsTo instead.
return $this->hasOne('account', 'account_url_id', 'id');
}
Now, fetching models:
// this part is .. amazing ;)
user::find( Auth::user()->id )->first();
// it does this:
Auth::user()->id // fetch user and get his id
user::find( .. ) // fetch user with given id, you have this user already above...
->first() // fetch first row from users table (not the one with id provided before)
so you want:
$account_urls = Auth::user()->workspaces()
->where('id', '=', 1)->first() // first fetches the result
// or simply
// ->find(1)
->accounts()->first()->accountUrl()
->pluck('url'); // this does 'SELECT url' and returns only this field instead of model
Just remember that:
$user->workspaces
$workspace->accounts
these are collections, so you can't call anything of the model on them, you need to get single model first.
I'm trying to tease out a logical problem that I'm having and I didn't know where else to ask!
I have two Objects whose relationship I'm trying to describe; the User and the Game. So, right now, I have that a User belongs to many Games, and that a Game belongs to many Users. What I'm trying to describe is the special instance when a User owns a Game. Presumably, this would simply be a column in the table for the owner_id. I am, however, struggling to establish how I can represent this in Eloquent. Do I need to create a new Object for the Game owner? Or can I use some kind of User role to describe this?
Game
class Game extends Eloquent
{
protected $guarded = array();
public static $rules = array();
// Game belongsToMany User
public function users()
{
return $this->belongsToMany('User');
}
// Need to identify the owner user.
}
User
class User extends Eloquent
{
protected $guarded = array();
public static $rules = array();
// User belongsToMany Game
public function games()
{
return $this->belongsToMany('Game');
}
}
I'm having difficulty even figuring out how to ask this in a clear and concise way, so if there's any more detail needed, please don't hesitate to ask.
What you need is thid table: games_owners. This is a migration schema for it:
Schema::create('games_owners', function($table)
{
$table->increments('id');
$table->integer('user_id');
$table->integer('game_id');
$table->timestamps();
});
This would be your User model:
class User extends Eloquent
{
protected $guarded = array();
public static $rules = array();
// User belongsToMany Game
public function games()
{
return $this->belongsToMany('Game', 'games_owners', 'user_id');
}
}
And you game model:
class Game extends Eloquent
{
protected $guarded = array();
public static $rules = array();
// Game belongsToMany User
public function users()
{
return $this->belongsToMany('User', 'games_owners', 'game_id');
}
// Need to identify the owner user.
}
And then you'll be able to do things like this:
$user = User::find(1);
foreach($user->games as $game) {
echo $game->name;
}