I am creating a data list and I print it with foreach, i would like it to display the data only if user_id matches the user_id reading the data. (previously I already have the user authentication created)
I want the users who enter to only see the data that contains their user_id.
I already made the relationship between the users table 'id' field with user_id
pass the data with:
public function index()
{
$servicios = App\Servicio::all();
return view('home', compact('servicios'));
}
How do I show the data that corresponds to the user_id of each one without others seeing their data??
You could set up a relationship inside the User.php model.
public function servicios() {
return $this->hasMany(Servicio::class);
}
Then in your controller:
public function index()
{
$servicios = auth()->user()->servicios;
return view('home', compact('servicios'));
}
You can get the user's list of services easily using Auth::user(), example:
User::with(['servicios'])->find(Auth::id());
you should get the user from your request, then filter by its id ...
public function index()
{
$user_id=app('request')->user()->id;
$servicios = App\Servicio::where('user_id',$user_id)->all();
return view('home', compact('servicios'));
}
the user will be present in your request, to make sure of that you should but
the route that use this method in (auth) middleware
Related
Database
I'm kind of new to databases and I made this small database, but I have problems fetching data from it.
Im trying to get all the racers from the logged in user, and it works properly, but if I enter $pigeons = $user->racer I only get back the racer table. I would like to know the attributes of the racers from the pigeons table aswell. I've made it work with query builder left joining the tables but I'm not sure why I set up this relationship if I can't use Laravel inner method.
In the User model I have these relationships:
public function pigeons(){
return $this->hasMany('App\Pigeon');
}
public function racers(){
return $this->hasManyThrough('App\Racer', 'App\Pigeon');
}
This is the Pigeon model:
public function user(){
return $this->belongsTo('App\User');
}
public function racer(){
return $this->hasMany('App\Racer');
}
}
And this is the Event model:
public function race(){
return $this->hasOne('App\Race');
}
public function racers(){
return $this->hasMany('App\Racer');
}
And this is what my EventsController looks like with the working alternative method and the commented not working.
public function upcoming(){
$id = auth()->user()->id;
$user = User::find($id);
$pigeons = DB::table('racers')->leftJoin('pigeons', 'racers.pigeon_id', '=', 'pigeons.id')->where('pigeons.user_id', '=', $id)->get();
//$pigeons = $user->racers;
return view('events.upcoming')->with('pigeons', $pigeons);
}
This is what I get with $user->racers or $user->racers()->get():
[{"id":1,"pigeon_id":14,"user_id":4,"event_id":1,"position":0,"created_at":null,"updated_at":null},{"id":2,"pigeon_id":15,"user_id":4,"event_id":1,"position":0,"created_at":null,"updated_at":null},{"id":3,"pigeon_id":16,"user_id":4,"event_id":1,"position":0,"created_at":null,"updated_at":null}]
And this is what I want to get, its not correct either since I should get id:1 but I want to pass to view these additional datas aswell like gender, color, ability (but they are in pigeons table not in racers).
[{"id":14,"pigeon_id":14,"user_id":4,"event_id":1,"position":0,"created_at":"2018-09-27 10:01:04","updated_at":"2018-09-27
10:01:04","gender":"hen","color":"blue","ability":38},{"id":15,"pigeon_id":15,"user_id":4,"event_id":1,"position":0,"created_at":"2018-09-27 10:01:04","updated_at":"2018-09-27
10:01:04","gender":"hen","color":"blue","ability":48},{"id":16,"pigeon_id":16,"user_id":4,"event_id":1,"position":0,"created_at":"2018-09-27 10:01:04","updated_at":"2018-09-27
10:01:04","gender":"cock","color":"blue","ability":11}]
To get the pigeons, what you would have to do is $pigeons = $user->racers()->get();. You can see an example of this in Laravel's official documentation https://laravel.com/docs/5.5/eloquent-relationships#introduction.
Database Table Relationship
What I did:
public function index(Request $request)
{
$company_feedback = $request->user()->company()
->get()->pluck('id')- >toArray();
$company = Company::whereIn('id',$company_feedback);
$feedback = $company->feedback;
return view('feedback.index', ['feedbacks' => $feedback]);
}
By using eloquent relationship, how to retrieve feedback data from a specific user id ? I want show feedback data which belong to current login user login id.
anyone could help? show me how to write the code in Index method in Feedback class.
Assuming you have two models User.php and Feedback.php
If you want to retrieve all feedback given by a current user
In your User.php
public function feedback()
{
//assuming you have user_id column in feedback table
return $this->hasMany("App\Feedback",'user_id');
}
In your controller
//all feedback given by the current user
$feedbacks = Auth::user()->feedback;
I have three tables which are User table, Events table, and Events_user table. I have four columns in the Events_user table which are :
Schema::create('events_user', function(Blueprint $table){
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('events_id')->unsigned()->index();
$table->foreign('events_id')->references('id')->on('events')->onDelete('cascade');
$table->integer('eventstatus')->unsigned()->index();
$table->timestamps();
});
I have a function which add an event base on the user id, show one user can have many of the events. But the event can share to other user. The function is like this :
public function store(EventsRequests $request){
$id = Auth::user()->id;
$events= Events::create($request->all());
$events->user()->attach($id); //Store the User_ID and the Event_ID at the events_user table.
Flash::success('Your event has been created!');
return redirect('/');//Return into home page
// return $events;
}
Then it will help me update my events_user table, but how do I update the column which is eventstatus?
Can anyone show me how could I update it? Cause I want to use the eventstatus help me determine if there is '1' then cant be edit, then the edit button will disappear.
How many way can accomplish to the function?
For the show page:
I have use the function when the user click the event that exist on the calendar view, then the javascript will pass the id back and redirect to the view with the id.
public function show($id){
// $user_id=Auth::user()->name;
$showevents = Events::findOrFail($id);
return view('events.show',compact('showevents','user'));
}
How about when i want to pass the eventstatus into the view? So i can check on my view, if the eventstatus equal to one, the edit button wont show up.
Updated relationship model
User.php
public function events(){
return $this->belongsToMany('App\Events');
}
Events.php
public function user(){
return $this->belongsToMany('App\User')->withPivot('eventstatus');
}
If you want to update the field while making the association, you can pass an array of field=>value pairs as the second parameter to the attach() method. You can read in the documentation here.
$events->users()->attach($id, ['eventstatus' => 1]);
If you want to update the field for an existing association, you can pass an array of field=>value pairs to the save() method:
$user = Auth::user();
$event = $user->events()->first();
$user->events()->save($event, ['eventstatus' => 1]);
If you want to access the field to read the data, you can access it through the pivot property:
$user = Auth::user();
foreach ($user->events as $event) {
echo $event->pivot->eventstatus;
}
In addition to all of this, you need to make sure your relationship definitions include access to the extra property:
// User class:
public function events() {
return $this->belongsTo(Event::class)->withPivot('eventstatus');
}
// Event class:
public function users() {
return $this->belongsTo(User::class)->withPivot('eventstatus');
}
Edit
updated answer for additional question
To get the information you're looking for, you need to be able to get to the pivot record. The pivot record is available on the models in the loaded relationship.
Since you have the Event, you need to go through the related User models, find the user you want (assuming the logged in user), and then get the status off of the pivot attribute on that user.
public function show($id)
{
// get your event
$showevents = Events::findOrFail($id);
// get your user
$user = Auth::user();
// default status to send to view
$status = 0;
// if there is a user...
if ($user) {
// find the user in the "user" relationship
// NB: calling "find" on a Collection, not a query
$eventUser = $showevents->user->find($user->id);
// if the user is associated to this event,
// get the status off the pivot table,
// otherwise just set the default status
$status = $eventUser ? $eventUser->pivot->eventstatus : $status;
}
// add your status to the data sent to the view
return view('events.show', compact('showevents', 'user', 'status'));
}
In addition to all this, make sure both relationship definitions include the ->withPivot('eventstatus'). You want to make sure you can get at it from both sides, if need be.
Can you share your event and user model relationship code?
so , it will help me to get into deep.
OR
you can try this in event model like:
public function user()
{
return $this->belongsToMany('App\Event')
->withPivot('eventstatus')
->withTimestamps();
}
then while updating you can do something like this iam not sure but hope this help.
$events->user()->attach($id,['eventstatus' => 1]);
Thanks
For fetching extra column:
public function show($id){
$showevents = Events::findOrFail($id);
$event_status = $showevents->pivot->eventstatus;
return view('events.show',compact('showevents','event_status'));
}
but for that you have to define this column in models:
// User class:
public function events() {
return $this->belongsTo(Event::class)->withPivot('eventstatus');
}
// Event class:
public function users() {
return $this->belongsTo(User::class)->withPivot('eventstatus');
}
Something very basic but I'm having a hard time solving this.
I have a list of users in the database that show as online users. I am fetching these users by their user_id
Model
public function scopeloggedInUser($query){
return $query->select('user_id')->get();
}
when I var_dump or dd it shows that its a collection of a list of currently logged in users. (Said it was super simple).
I need to fetch those individual users. How do I dilute this to the individual user within the Online Model.
Within the Controller
public function index(Online $online)
{
$activeuser = $online->loggedInUser();
return view('user.user', compact('activeuser'));
}
In your online-model specify a relationship to the real user like this:
public function user()
{
return $this->hasOne('App\User');
}
In your view you can now access each user in your foreach-loop like this:
foreach ($activeusers as $user)
{
echo $user->user->username; // or whatever fields you need
}
But to be honest: in your case I wouldn't set up a new database table and new model if you need this functionality.
Move your logic to your User model and add a boolean field to your user table and change your query-scope to this (again: in your user model)
public function scopeOnline($query){
return $query->where('online', 1);
}
You also shouldn't do a get() within a scope because then you have no more access to the query builder. For example: you want all logged in users that are female.
With get: not pretty.
Without get:
User::online()->where('gender', '=', 'female')->get();
I have three tables like this:
**Users**
id
**Posts**
id
user_id
**Favorites**
id
user_id
post_id
Currently, I made it so when I query my posts for display, it pulls all the related user data who created the post with that row which is great! But what I'm trying to do now is also add to see if the user Authorized (Logged in) has favorited the post (row) so I can display to that they already favorited it. I don't want to re-query for every post (i think its called the N+1 problem?). I'm using Laravel4
Post model
class Post extends Eloquent{
public function user(){
return $this->belongsTo('User');
}
User model
public function posts(){
return $this->hasMany('Post');
}
PostsController
public function index()
{
$posts = Post::with('user')->paginate(25);
return View::make('index', compact('posts'));
}
Step 1. Add favorites relationship in Post model.
public function favorites() {
return $this->hasMany('Favorite');
}
When querying the Model.
$auth_user_id = Auth::user()->id;
$posts = Post::with(array('user', 'favorites' => function($query) use ($auth_user_id){
$query->where('user_id', '=', $auth_user_id);
}))->get();
For more information refer to the eager load constraints,
http://laravel.com/docs/eloquent#eager-loading
Adding a many-to-many relationship using the favorites table as pivot would be one approach.
Add favorites relationship in User model:
public function favorites() {
return $this->belongsToMany('Post', 'favorites');
}
You should then be able to get all favorites by simply accessing
Auth::user()->favorites
To find whether the current post is a favorite, use
$isFavorite = Auth::user()->favorites->has($post->id);