laravel where on relationship table - php

I am using laravel, I have a main table with 'projects' and a table with 'users', an intermediate table linking the two as a many-to-many relationship.
Now I want to display a list of projects, but if they are over 'projects.max_people' then they should be hidden from this list, how do I do this in laravel?
The problem is im 'get()'ing the users in the view, after I did Project::get()... how do I add this where condition?

You should create a new object called ProjectUser or so. In this object should contain a 'project_id' and 'user_id'.
Then, your Project model would look something like this:
<?php
class Project extends \Eloquent
{
protected $table = 'projects';
public function projectUsers(){
$this->hasMany('ProjectUser', 'project_id');
}
}
The User class:
<?php
class Project extends \Eloquent
{
protected $table = 'projects';
public function projectUsers(){
$this->hasMany('ProjectUser', 'user_id');
}
}
The ProjectUser class:
class ProjectUser extends \Eloquent
{
protected $table = 'project_users';
public function project(){
$this->belongsTo('Project'`enter code here`, 'project_id');
}
public function user(){
$this->belongsTo('User', 'user_id');
}
}
Now, you can get the users of a project like so:
$projects = Project::with('projectUsers.user')->get();
When looping through these objects you can access the user like this:
#foreach($projects as $project)
#foreach($project->projectUsers as $projectUser)
{{ $projectUser->user->id }}
#endforeach
#endforeach

Related

Sort belongsToMany relation base on field in belongTo relation Laravel Eloquent

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.*)

Problem with Laravel Eloquent - relation not working

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();
}
}

Obtaining a list of non-linked models, in many_to_many relations, using Laravel Eloquent

I have a User-Roles model, using Laravel 4 where a user can have many roles, using Eloquent. I can access all roles linked to a user easily using this code :
class User extends Model {
protected $table = 'user';
protected $fillable = array('name');
public function rolesLinked() {
return $this->hasMany('App\UserRoleLink', 'user_id');
}
}
I've been trying to obtain the roles that are not linked to a user, to display on the specific user's page in a select box. Using this function, included in the User class.
public function rolesNotLinked() {
$user = this
$roles = Roles::whereDoesntHave('App\UserRoleLink',function($query) use ($user){
$query->where('user_id',$user->id);
});
}
The problem is, calling this function gives me the following error.
Call to undefined method Illuminate\Database\Query\Builder::App\UserRoleLink()
I've tried using has with < 1 to see if the function was problematic, but after reading this and the online source code, the function call pretty much does what I've tried.
Is something wrong in my function call, or have I messed up configurations somewhere?
For reference, here are my other Model classes:
class UserRoleLink extends Model{
protected $table = 'user_role_link';
protected $fillable = array('role_id','user_id);
public function role() {
return $this->hasOne('App\Role', 'role_id');
}
}
class Role extends Model{
protected $table = 'role';
protected $fillable = array('name');
}
EDIT: I've found out that I messed up by fillables when I copy-pasted. It didn't fix the issue, but I guess that's one step closer.
To use whereDoesntHave method, you must add the relation in your Role Model.
class Role extends Model{
protected $table = 'role';
protected $fillable = array('name');
public function UserRoles() {
return $this->hasMany('App\UserRoleLink', 'id');
}
}
Also, the whereDoesntHave method first parameter is not thte model but the function of the relation:
public function rolesNotLinked() {
$user = this
$roles = Roles::whereDoesntHave('UserRoles',function($query) use ($user){
$query->where('user_id',$user->id);
});
}

Laravel Eloquent 'belongs to' relationship books and its category

I'm trying to print all books' name in 'books' table and its category associated. But it doesn't show any content nor error messages.
Model::Book.php
class Book extends Eloquent{
protected $table ='books';
public function bookCat()
{
return $this->belongsTo('BookCategory');
}
}
Model::BookCategory.php
class BookCategory extends Eloquent{
protected $table ='book_categories';
}
Controller::route.php
Route::get('/', function()
{
$books = Book::all();
return View::make('books')
->with('books', $books);
});
View::books.blade.php
#foreach ($books as $book)
<li>{{ $book->book_name }}</li>
- <small>{{ $book->bookCat }}</small>
#endforeach
Table::books
(int)id, (string)book_name, (int)category_id
Table::book_categories
(int)id, (string)category
Add the relationship to BookCategory.
class BookCategory extends Eloquent{
protected $table ='book_categories';
public function books() {
return $this->hasMany('Book');
}
}
Your local key doesn't match the model names, either, so you would need to specify that in the relation:
class Book extends Eloquent{
protected $table ='books';
public function bookCat()
{
return $this->belongsTo('BookCategory', 'category_id');
}
}
You may also want to eager-load the categories in your controller, as your query is for the books:
$books = Book::with('bookCat')->get();

Get value from view

I have two table User & Article the relationship between tables are
Model:
class Article extends Eloquent {
public static $table = 'article';
public function User()
{
return $this->has_one('user', 'id');
}
and
class User extends Eloquent {
public static $table = 'user';
public function Article()
{
return $this->belongs_to('article', 'id_user');
}
I want to get name value from User directly on Article view but don't works with error
Trying to get property of non-object
My Controller:
public function action_index()
{
$Article = Article::order_by('id')->paginate(10);
return View::make('article.index')->with('$articles', $Article);
}
My View:
#foreach ($articles->results as $Arti)
<tr>
<td>{{$Arti->id}}</td>
<td>{{$Arti->tag}}</td>
<td>{{$Arti->user->name }}</td> <------ ERROR
<td>{{$Arti->content}}</td>
<td>{{$Arti->date}}</td>
<td>
Have a look at the below, a few things are different to yours...
Article belongs_to User (not has_one)
User has_many Article (not belongs_to)
Your relationships should be named in lowercase, plural for has_many (i.e. articles or user)
Your relationship subjects should be class names (i.e. Article or User)
Foreign keys should be name relationship_id, i.e. user_id
Add ::with() to your query to eager load relationships
When you paginate you need to access ->results in your view
class Article extends Eloquent {
// 3: lowercase 'user'
public function user()
{
// 1: Article belongs to User
// 4: class name 'User'
// 5: Foreign key on article table is user_id
return $this->belongs_to('User');
}
}
// models/user.php
class User extends Eloquent {
// 3: lowercase plural 'articles'
public function articles()
{
// 2: User has many Articles
// 4: class name 'Article'
return $this->has_many('Article');
}
}
// controllers/articles.php
class Article_Controller extends Base_Controller {
public $restful = true;
public function get_index()
{
// 6: Eager load the user relationship, ::with('user')
$articles = Article::with('user')->order_by('id')->paginate(10);
return View::make('articles.index', compact('articles'));
}
}
// views/articles/index.blade.php
// 7: access $articles->results from the paginator
#foreach ($articles->results as $article)
<h1>{{ $article->title }}</h1>
<p>By {{ $article->user->name }}</p>
#endforeach
{{ $articles->links() }}

Categories