navigating to other user's profile (laravel 5.2) - php

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.

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

How to Pass Data From One View to Another in Laravel?

I am quite new to Laravel
I have two views
Book
Read
The Book View displays a single book
<section class="cont-readingone">
<div class="container">
<div class="row row-grid">
<div class="col-md-6">
<div class="row">
<div class="col-md-6">
<div class="cont-reading-image">
<img src="{{ $book->image_url }}" alt="trending image" />
</div>
</div>
<div class="col-md-6">
<div class="out-box">
<h2>{{ $book->name }}</h2>
<h3>{{ $book->author->name }}</h3>
<br>
Start Reading<br><br>
<img src="\images\cart-buy.png" width="13px"/> Buy
</div>
</div>
</div>
</div>
In my controller, I was able to achieve it using
public function show(Book $book) {
$relatedBooks = Book::where('author_id', $book->author_id)
->where('id', '!=', $book->id)
->get();
return view('book')->with('book', $book)->with('relatedBooks', $relatedBooks);
}
In my web.php
Route::get('/books/{book}', [BooksController::class, 'show'])->name('book');
What I am trying to achieve is that, when I click Start Reading on
the Single Book Page, it takes me to another view page (Read) but it takes the book id that I clicked.
In the Read View I have this code,
<script>
"use strict";
document.onreadystatechange = function () {
if (document.readyState == "complete") {
window.reader = ePubReader("{{ $book->epub_url }}", {
restore: true
});
}
};
</script>
My problem is that I don't know how to take the id of the book that I
click and Pass it to the Read View
I will be glad if someone can explain the logic to me as I am confused.
To do via POST
//Book View
//change Start Reading to
<form action="{{ route("your.route.to.read") }}" method="POST">
#csrf
<input name="book_id " value ={{$book->id}} hidden>
<button type="submit">Start Reading</button>
</form>
//your Route will be
Route::get('/read',YourReadController#yourFunction)->name('your.route.to.read');
//your controller will be
public function yourFunction(Request $request)
{
//book id is in $$request->book_id
//your operation here
return view('read')->with('data',$dataYouWantToSend);
}
To do via GET
//Book View
//change Start Reading<br><br> to
Start Reading
//route for get will be
Route::get('/read/{book_id}',YourReadController#yourFunction)->name('your.route.to.read');
//your countroller will be
public function yourFunction($book_id)
{
//book id is in $book_id
//your operation here
return view('read')->with('data',$dataYouWantToSend);
}

Fetch first image from foreign key table Laravel

Reference: Fetch first image from foreign key table but this time in Laravel.
I started playing with Laravel and I want to take first image from every post and show these in my blade.
$secondpost = DB::table('posts')
->orderBy('id', 'desc')
->skip(1)
->take(8)
->get();
foreach ($secondpost as $spost)
$secondph = DB::table('post_images')
->select('filename')
->where('post_id', $spost->id)
->limit(1)
->get()
->pluck('filename');
return view ('pages.index', compact('firstp', 'fph', 'secondpost', 'secondph'));
<div class="row">
#foreach ($secondpost as $secondp)
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 post-ab">
<div class="row">
#foreach ($secondph as $sph);
<img src="{{url($sph)}}" class="imgpost" alt="">
#endforeach
<div class="bottomleft">
<p class="ab-desc">{{$secondp->marca}} {{$secondp->model}}</p>
<p class="ab-desc">{{$secondp->pret}} Eur</p>
</div>
</div>
</div>
#endforeach
</div>
This code load only one image for every img src. Post_id is foreign key for posts table id.
There are few things you need to confirm.
You have created models for the table like Post for posts table and PostImages for post_images table. If not, follow the documentation. https://laravel.com/docs/5.8/eloquent
You have created the hasMany relationship in your post model with post_images. Like:
In Post model.
/**
* Get the images for the post.
*/
public function images()
{
return $this->hasMany('App\PostImage');
}
Then change in your controller to use early loading, Like:
$secondpost = \App\Post::with("images")
->orderBy('id', 'desc')
->skip(1)
->take(8)
->get();
And now the view looks like:
<div class="row">
#foreach ($secondpost as $secondp)
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 post-ab">
<div class="row">
#php
$image = $secondp->images->first();
#endphp
<img src="{{url($image->filename)}}" class="imgpost" alt="">
<div class="bottomleft">
<p class="ab-desc">{{$secondp->marca}} {{$secondp->model}}</p>
<p class="ab-desc">{{$secondp->pret}} Eur</p>
</div>
</div>
</div>
#endforeach
</div>
Solution: 2
You can create another relationship with hasOne to get a single image like:
// In your Post model.
/**
* Get the default image for post.
*/
public function default_image()
{
return $this->hasOne('App\PostImage')->orderBy("id");
}
Make change in controller to use ->with("default_image").
And in view you can just use like:
$secondp->default_image->filename

Laravel view links and web.php routes messed up

I'm making a forum with themes and topics. If a user clicks on a theme, he/she gets to see all the topics within that theme. Here we encounter the first problem. In the theme.blade.php I have a title: <span class="card-title">{{ $theme->theme_title }} - Topics</span>. This title is supposed to show the title of the theme that the user clicked on. But it shows (just a wild guess) some random theme title from the database that is not even connected to this topic.
Now I made an extra view for the user. If the user clicks on a topic from the selected theme. He/she is supposed to redirect to the topic that he/she clicked on but instead its shows (again) some random topic from the database that is not connected to the topic/theme at all. Instead of the topic that the user clicked on. In this GIF http://imgur.com/a/vOQFT you can see the problem If u look at the profile picture and username. Maybe the problem is in the Web.phpor somewhere else, I don't know. Sorry for the long story but I couldn't figure out how say this in a better way. I think I switched some things up in the code.
Here is the every file of code where this problem may occur
Web.php
Route::get('/', 'ThemesController#index')->name('home');
Route::get('/theme/{theme_id}/topics', 'ThemesController#show')->name('showtheme');
Route::get('/theme/{theme_id}/topics/{topic_id}', 'TopicsController#show')->name('showtopic');
Route::group(['middleware' => 'App\Http\Middleware\AdminMiddleware'], function() {
//THEMES
Route::get('/theme/{theme_id}/edit', 'ThemesController#edit')->name('edittheme');
Route::patch('/theme/{theme_id}/edit', 'ThemesController#update')->name('updatetheme');
Route::get('/theme/create', 'ThemesController#create')->name('createtheme');
Route::post('/theme/create', 'ThemesController#save')->name('savetheme');
Route::delete('/theme/{theme_id}/delete', 'ThemesController#destroy')->name('deletetheme');
//TOPICS
Route::get('/theme/{theme_id}/topics/{topic_id}/edit', 'TopicsController#edit')->name('edittopic');
Route::patch('/theme/{theme_id}/topics/{topic_id}/edit', 'TopicsController#update')->name('updatetopic');
Route::get('/theme/{theme_id}/topics/create', 'TopicsController#create')->name('createtopic');
Route::post('/theme/{theme_id}/topics/create', 'TopicsController#save')->name('savetopic');
Route::delete('/theme/{theme_id}/topics/{topic_id}/delete', 'TopicsController#destroy')->name('deletetopic');
});
Route::get('user/profile', 'UserController#profile')->name('showprofile');
Route::post('user/profile', 'UserController#update_avatar');
Theme.blade.php (The list of every topic within the theme)
<div class="col s12">
<div class="card">
<div class="card-content"><span class="card-title">{{ $theme->theme_title }} - Topics</span>
<div class="collection">
#foreach($topics as $topic)
<a href="{{ route('showtopic', ['theme_id' => $theme->id, 'topic_id' => $topic->id ]) }}" class="collection-item avatar collection-link"><img src="/uploads/avatars/{{ $topic->user->avatar }}" alt="" class="circle">
<div class="row">
<div class="col s6">
<div class="row last-row">
<div class="col s12"><span class="card-title">{{ $topic->topic_title }}</span>
<p>{!! str_limit($topic->topic_text, $limit = 125, $end = '...') !!}</p>
</div>
</div>
<div class="row last-row">
<div class="col s12 post-timestamp">Posted by: {{ $topic->user->username }} op: {{ $topic->created_at }}</div>
</div>
</div>
<div class="col s2">
<h6 class="title center-align">Replies</h6>
<p class="center replies">{{ $topic->replies->count() }}</p>
</div>
<div class="col s2">
<h6 class="title center-align">Status</h6>
<div class="status-wrapper center-align"><span class="status-badge status-open">open</span></div>
</div>
<div class="col s2">
<h6 class="title center-align">Last reply</h6>
<p class="center-align"></p>
<p class="center-align">Tijd</p>
</div>
</div>
</a>
#endforeach
</div>
</div>
</div>
</div>
ThemesController.php (Only show method)
public function show($id)
{
$theme = Topic::find($id)->theme;
$topics = Theme::find($id)->topics;
return view('themes.theme')->with('topics', $topics)->with('theme', $theme);
}
TopicsController.php(Only show method)
public function show($id)
{
$theme = Theme::find($id);
$topic = Topic::find($id);
return view('topics.topic')->with('theme', $theme)->with('topic', $topic);
}
Thanks for looking at my code. This problem has been sitting here for quite a while and I want to move on. Thanks for your help!
Your controller code simply finds the theme with ID $id, and the topic (singular!) with ID $id. That particular topic may not appear in that particular theme at all. They likely have nothing to do with each other.
To find the topics belonging to the theme with ID $id, you would do this:
$theme = Theme::find($id)->with('topics');
(this assumes your model relationships are set up correctly, you have not show us those). See the docs on eager loading.
To access the topics in your view, do something like this:
#foreach ($theme->topics as $topic)
...
{{ $topic->user->username }}
...
While developing, you can simply
return $theme;
in your controller to see the structure of the data, so you can work out how to handle and iterate over it.

Determine whether user profile belongs to current user in Laravel

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.

Categories