Apologies if the title doesn't completely make sense... I wasn't sure if the exact terminology for the linking of models are the associated data in their controllers.
I'm trying to paginate a table with the posts created by a user.
I managed to paginate it previously, without the user_id in the posts table. But I've added the user_id to the posts table, and run the migration which works fine.
The following is my Post model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
And this is my User model:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['name', 'email', 'password',];
protected $hidden = ['password', 'remember_token',];
public function posts() {
return $this->hasMany('App\Post');
}
}
And this is the relevant section of the post controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\User;
use Session;
use Carbon\Carbon;
class PostController extends Controller
{
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('posts.index')->with('posts', $user->posts);
}
I thought that it would simply be a case of appending ->paginate(5) to the $user in the PostController, but that doesn't appear to work.
I get the following:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$posts
I've tried including the {!! $posts->links() !!} in the posts.index view before the #foreach but that gives:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$posts
I'm trying to learn Laravel basics by creating this crud application, and have tried combining two tutorials together, but I'm clearly missing something.
You can call ->paginate() on the relationship like this (also I've removed the unnecessary user query, since auth()->user() will execute it already):
public function index()
{
$user = auth()->user();
$posts = $user->posts()->paginate();
// Or with 1 line: $posts = auth()->user()->posts()->paginate();
return view('posts.index')->with('posts', $posts);
}
Related
I want to make the following query with Eloquent:
$nota=DB::table('notas')
->join('users', 'users.id', '=', 'notas.id_user')
->select('notas.id','notas.nombre', 'notas.descripcion', 'users.name AS user_name', 'users.email')
->first();
I try to make the relation in the models and called like this, in my controller:
public function show($id)
{
$nota = Nota::with(['user','nota'])->first();
print_r($nota);
return view("notas.detalle", compact("nota"));
}
But i get the follow error:
Illuminate\Database\Eloquent\RelationNotFoundException
Call to undefined relationship [nota] on model [App\Nota].
My models looks like this:
Nota.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Nota extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
User.php:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
public function notas()
{
return $this->hasMany('App\Nota');
}
}
The problem is with your understanding of relationship. You don't make any relationship named nota but you are using it and ridiculously with the same model. So firstly make the relationship right using naming convention.
In Nota model
public function user()
{
return $this->belongsTo('App\User','id_user');
}
In User model
public function notas()
{
return $this->hasMany('App\Nota','id_user');
}
And now in controller
$nota = Nota::with('user')->first();
return view("notas.detalle", compact("nota"));
Look this is an eager loading. You can lazy load the relationship too.
In view now you can access object property like
{{ $nota->nombre }}
And relationship object like
{{ $nota->user->email }}
The problem is with this function Nota::with(['user','nota'])->first()
Why do you want nota with nota. it's sounds ridiculous isn't it?
So just remove it, then everything will work fine.
$nota = Nota::with(['user'])->first();
return view("notas.detalle", compact("nota"));
I have Users_group model in my Laravel project.
Code:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Users_group extends Model
{
use Notifiable;
protected $table = 'users_groups';
protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];
public function getGroupData()
{
return $this->hasOne('App\Group','id','group_id');
}
}
And when I want to get data from this model I use this my custom method:
$data = App\Users_group ::get();
It's working great
I want to get the data from model with condition not like this:
$data = App\Users_group::where('group_id','>',5)->get();
I need to put the condition inside the model file thats make the model return the data everytime I call User_group::get() return it when condition inside the model.
Thanks!
You can use query scopes to achieve this. Query scopes allow you to add a global constraint to a model.
In your case, you could add the following boot method to your model:
protected static function boot()
{
parent::boot();
static::addGlobalScope('groupOver5', function (Builder $builder) {
$builder->where('group_id', '>', 5);
});
}
try this one in by using scope in model
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Users_group extends Model
{
use Notifiable;
protected $table = 'users_groups';
protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];
public function scopeGetGroupData($query,$value,$opertor = '>')
{
return $query->where('group_id', $opertor, $value);
}
}
get data in controller like this u can pass also parameter in method
App\Users_group::GetGroupData($value)->get();
I have a set of relationships that looks like this:
The users and agencies have a lot of data stored in them, in addition to the pivot tables you see there.
What I'd like to do is find the agencies or users that match the preferences of the currently logged in individual, whether they are an agency or user.
It's a straight comparison, so nothing fancy. But I honestly have no idea how to write the eloquent query to account for the pivot tables. Can someone point me in the right direction?
I'm looking at something like this, which is understandably failing:
$loggedinagency = Auth::user()->id;
$match_user_agency = User::with('work_prefs')
->where('work_prefs', 'like',
Agency::find($loggedinagency)->work_prefs)
->get();
Edit: The relationships are declared like so:
User:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
protected $table = 'users';
public function work_prefs() {
return $this->belongsToMany('App\Work_Prefs', 'preference_user', 'user_id', 'preference_id');
}
}
Agency:
<?php
namespace App;
class Agency extends Authenticatable
{
use Notifiable;
protected $table='agencies';
public function work_prefs() {
return $this->belongsToMany('App\Work_Prefs', 'agency_preference', 'agency_id', 'preference_id');
}
}
Work Preferences:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Work_Prefs extends Model
{
protected $table = 'work_prefs';
public function user() {
return $this->belongsToMany('App\User', 'preference_user', 'preference_id', 'user_id');
}
public function agency() {
return $this->belongsToMany('App\Agency', 'agency_preference', 'preference_id', 'agency_id');
}
}
I have a problem posting data in Laravel 5. I've done a page that post stuff on a controller that would create a new row on a database, according to Eloquent class. But when I post that, I receive a blank page and nothing works.
This is my controller, focused on the affected class:
<?php namespace App\Http\Controllers;
use App\T_subject;
use App\T_reservation;
use Date;
use Request;
use Config;
use Validator;
use Auth;
class TutoringController extends Controller {
public function reserve(Request $request)
{
$reservation = new T_reservation;
$reservation->user_id = Auth::user()->id;
$reservation->subject_code = $request->input('subject');
$reservation->date = $request->input('date');
$reservation->topic = $request->input('topic');
$reservation->save();
return redirect('/tutoring/view/'.$request->input('subject'));
}
}
This is my Eloquent model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class T_reservation extends Model {
protected $table = 't_reservations';
public function user()
{
return $this->belongsTo('App\User');
}
}
And my routes file:
<?php
Route::post('tutoring/reserve', ['middleware' => 'auth', 'uses' => 'TutoringController#reserve']);
Where's the problem?
In your routes file there is no definied route for your final redirection: '/tutoring/view/'.$request->input('subject').
Also, your model have no fillable property, which should list properties for which you can make a mass assignment. For instance something like this:
protected $fillable = ['user_id', 'subject_code', 'date', 'topic'];
I'm making a small work with Laravel and using Zizaco Entrust.
While logged in as Administrator I want to see all Roles of a specific user.
I'v searched for a while but didn't find any clue...
How can I do it using Entrust or shall I use SQL queries?
In your User class add
public function roles()
{
return $this->belongsToMany('Role','assigned_roles');
}
Then you can get all roles for a specific user
$user = User::with('roles')->find(1);
$roles = $user->roles;
If you are using Zizaco\Entrust you don't need new roles method in User model. Roles method already exist in EntrustUserTrait class. You only need this line inside User class:
use EntrustUserTrait;
like this:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Authenticatable
{
use EntrustUserTrait; // add this trait to your user model
.....
}
In your UsersController you can select users with their roles (index method):
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
class UsersController extends Controller
{
protected $users;
public function __construct(User $users)
{
$this->users = $users;
parent::__construct();
}
public function index()
{
$users = $this->users->with('roles')->paginate(25);
return view('users.index', compact('users'));
}
In your blade loop $user->roles inside $users loop because $user->roles are collection even if user have only one role.
#foreach($users as $user)
#foreach($user->roles as $role)
{{ $role->display_name }}
#endforeach
#endforeach