Determine whether user profile belongs to current user in Laravel - php

In my application, I have the concept of a user profile. The information that gets displayed differs depending on whether the user is viewing their own profile or another user's profile. Here's a simplified view of UsersController#show:
public function show($id)
{
$user = User::findOrFail($id);
$currentUser = Auth::user();
return view ('users.show', compact('user', 'currentUser'));
}
In my view, I end up having to write code that looks like:
#if ($currentUser === $user->id)
<section class="container search-form visible-nav">
<div class="row">
<div class="col-xs-12">
#include ('partials._search')
</div>
</div>
</section>
#endif
This seems like a clumsy implementation, especially for a language like Laravel. Is there a more concise way to achieve the same result in my views?

Not really. You need to check if current user is the viewed user somewhere - either in the controller or in the view.
You could simplify your code a bit though:
public function show($id)
{
$user = User::findOrFail($id);
return view ('users.show', compact('user'));
}
#if (Auth::id() === $user->id)
<section class="container search-form visible-nav">
<div class="row">
<div class="col-xs-12">
#include ('partials._search')
</div>
</div>
</section>
#endif
There are some other options like returning different blade templates depending on whether the current user is the same as the viewed user, but if the only difference would be a few #ifs I would keep it in one template.

Related

Cannot find the way to make #if statement works in blade

I'm making a "teacher's" app, and I want to make a log-in page which changes depending if there's registered users in the database or not.
I want to make a redirection button to a create user page if there aren't auth users in database, and to make a select user view if the database have one or more users.
The problem is that I don't know how to exactly do this, 'cause the view always shows me the first statement (what I've got in the if), also if in the database are registered users. Can anyone help me with this please?
This is the blade file:
#if (empty(Auth::user()->id))
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Button</button>
</div>
</div>
#else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
#endif
Here you have the controller index method:
public function index()
{
$users = User::all();
return view('/', compact('users'));
}
And finally here you have the page:
The following code is the sample for it, kindly replace code accordingly
#if(!$user)
//show button
#else
//dont show button
#endif
I think your question is you want to check if there is user in database.
So no need to check if the user authenticated but to check if there is user on the database.
In your controller
public function index() {
return view('/', ['users' => User::all()]);
}
and in your blade file
#if(!$users)
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Button</button>
</div>
</div>
#else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
#endif
This function will get the current authenticated user: Auth::user(). I guess what you are trying to achieve is #if(empty($users)) where $users is the variable you are passing on controller.
If you want to verify if the user that accessed to that view is authenticated you can simply use #auth and #guest.
Also i would suggest you to change your button to an <a> tag and your href would be <a href="{{ route('route.name') }}" where route.name would be defined in your routes file.
in your controller:
you can create a folder inside views called users and then the index.blade.php (views/users/index.blade.php)
public function index()
{
$users = Users::all();
return view('users.index')->with('users', $users);
}
in your view:
#if(count($users) < 1)
...
#else
...
#endif
count is validating if the $users array length is less then 1 (in other words if the array is empty).
Alternative you can you isEmpty()
#if($users->isEmpty())
...
#else
...
#endif

Laravel compact is not working

I'm trying to make a posting system, with a resource routing combination on the posts. When I try to run the app to view the posts, it returns an error stating that the posts could not be found within the view. I have the controller code for the index and the show functions:
public function index()
{
$posts = Post::latest()->get();
return view('view', compact('posts'));
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
The view that I have for the app uses the post variable to display the posts:
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-2">
<div class="panel panel-default">
<!-- Posts will be displayed on the same panel -->
<div class="panel-body" id="view">
#foreach($posts as $post)
<article id="post">
<a href="/view/posts{{ $post->id }}">
{{ $post->title }}
</a>
<div class="body">
{{ $post->body }}
</div>
<!-- Footer for posts will include interaction features -->
</article>
#endforeach
</div>
</div>
</div>
</div>
</div>
Is there something that the laravel installation isn't doing correctly? Is the compact function set up correctly?
Your controller index function should be something like this:
public function index()
{
$posts = Post::get();
return view('posts.index', compact('posts'));
}
The return of the index action is wrong
return view('view', compact('posts'));
Change 'view' with 'posts'
Use compact('posts')
If you're a beginner checkout the laracasts video series to get a good understanding of the Laravel framework.

navigating to other user's profile (laravel 5.2)

I want that a login user can goto other user's profile pages where all his posts and other stuff is displayed.
what i tried is given below:
my route:
Route::get('/myplace/{username}' , [
'uses' => 'PostController#getmyplace' ,
'as' => 'myplace' ,
'middleware' => 'auth:web'
]);
PostController:
public function getmyplace($username)
{
$user = User::where('username', $username)->first();
if(!$user)
abort(404);
$posts=Post::where(function($query){
$query->where('user_id',Auth::user()->id)
->orWhereIn('user_id',Auth::user()->friends()->lists('id')
);
})
->orderBy('created_at','desc')->get();
$accounts=Account::orderBy('updated_at','desc')->limit(1)->get();
return view('myplace',['user'=>$user,'posts'=>$posts,'accounts'=>$accounts]);
}
my view:
> #if (!$posts->count())
> <p>{{$user->getNameOrUsername() }} hasn't posted anything, yet.</p>
> #else
> #foreach ($posts as $post)
> #if(Auth::user()== $post->user)
>
> <div class="panel panel-default">
> <div class="panel-heading">
> <div class="row">
> <section class="col-md-2 col-xs-2"> <img id="imagesize2" src="images/g.jpg" class="img-circle" data-action="zoom"/></img>
> </section> <section class="col-md-5 col-xs-offset-1 col-xs-5">
> <a id="alink13" href=""><h5
> id="alink14">{{$post->user->getNameOrUsername() }}</h5></a>
> <p> on {{$post->created_at}} </p> </section>
> </div>
> <div class="panel-content">
> <div class="row" id="fetch">
> <section class="col-md-12" data-postid="{{ $post->id }}">
> <p id="post">{{$post->body}}</p>
> <div class="interaction" >
> #if(Auth::user()==$post->user)
> Edit
> <a id="remove2" href="{{route('post.delete',['post_id' => $post->id])}}">Delete</a>
> #endif
> </div>
> </section>
> </div>
> </div>
I passed the username parameter but that didn't gave the desired output.
Anything i need to provide just tell me.
Your problem is here
$query->where('user_id',Auth::user()->id)
->orWhereIn('user_id',Auth::user()->friends()->lists('id')
);
Your query is selecting data for Auth::user() instead of $user
$posts=Post::where(function($query) use ($user) {
$query->where('user_id',$user->id)
->orWhereIn('user_id',$user->friends()->lists('id')
);
})
->orderBy('created_at','desc')->get();
EDIT add use ($user) when declaring the anonymous function
Also you could remove the query if you have setup eloquent relations correctly.
$posts = $user->posts; // example
EDIT 2 remove
#if(Auth::user()== $post->user)
You are selecting posts (in your controller) that DONT belongt to you. So don't check they belong to you in the view.
EDIT 3
For details have a look into the discussion. The current state is that actually another reference to a user is needed in the posts table. This reference defines on whoms "profile" the post as made on. Therefore it could be called target_id and references id on users table.
In a next step the route has to be changed so that a user id is passed (could also be passed in the request body ofcourse) e.g.
/user/{id}/profile
The controller then takes the passed $id parameter as target_id and the current user (Auth::user()) as user_id (creator of the post)
Finally the query can be adapted to actually select every post of the user himself + every post where he is the target
$posts=Post::where(function($query) use ($user) {
$query->where('user_id',$user->id)
->orWhere('target_id',$user->id);
})
->orderBy('created_at','desc')->get();
Ofcourse the $user needs to be selected in the different requets and routing and internal redirects need to be adapted with regards to the changes.

how to display My table data in Laravel 5.2

I have collaborators table in My Laravel app see this following
I need collaborator_id print in My index.blade.php file who equel with Auth::user()->id to logged with the system. I wrote following code in My Collaboration Model
public function scopeColabo($query){
return $query->where('collaborator_id',Auth::user()->id);}
and this is My ProjectCollaboratorController function
public function index(){
$collaborators = Collaboration::colabo()->getreturn view('collaborators.index')->withCollaboration($collaborators);}
and this is My index.blade.php
<div class="container">
#if($collaboration)
<div class="row">
#foreach ($collaboration as $proj)
<div class="col-md-3" style="border:1px solid #ccc;margin-left:5px;">
<h2>{!! $proj->project_id !!}</h2>
<p>Tasks: 0</p>
<p>Comments: 0</p>
<p>Attachments: 0</p>
</div>
#endforeach
</div>
#endif
#if($collaboration->isEmpty())
<h3>There are currently no Collaboration</h3>
#endif
</div>
But when I click collaboration link index.blade.php file generate
There are currently no Projects
but in My table there is data....how can print collaborator_id in collaboration Table relete with current logged user?
Try to use ->with() instead of ->withCollaboration:
public function index() {
$collaborators = Collaboration::colabo()->get();
return view('collaborators.index')->with(compact('collaborators'));
}
or just pass your data as second parameter:
public function index() {
$collaborators = Collaboration::colabo()->get();
return view('collaborators.index', compact('collaborators'));
}
The problem is with the collaborator_id in the table which is used to log to test the system:
In the tests, in the logging account, data should match with collaborator data, so collaborator_id should match with the logged user id.

Blank page on laravel 5

I just try to create a profile page i create a Route like this:
Route::get('profile/{id}/{name}','ProfileController#index');
and the index function like this :
public function index($id,$name)
{
$user = \App\User::find($id);
return view('pages.profile',compact('user'));
}
profile view:
#extends('app')
#section('content')
<div class="container" style="margin-top: 50px;padding: 30px;">
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
<div class="proPic"><img src="{{user->image}}" class="img-responsive" alt="Image"></div>
</div>
</div>
</div>
#endsection
but when I lunch the link i get a blank page
If you have a default installation, you probably need to have:
#extends('layouts.app')
instead of
#extends('app')
and change
{{user->image}}
to
{{ $user->image }}
Your code looks clean, a blank page can occur when laravel doesn't displays errors. I'd recommand you to :
1- Check the server response (HTTP code, content...)
2- Check your logs, maybe you'll discover a problem of configuration

Categories