undefined variable Posts - laravel

I am trying to complete a search filter feature for my website however i am recieving the following error:
Undefined variable: posts (View:
#foreach($posts as $distance)
<option value="{{$distance->distance}}">{{ $distance->distance}}</option>
#endforeach
Here is my search.blade.php (error occuring:
#foreach($posts as $distance)
<option value="{{$distance->distance}}">{{ $distance->distance}}</option>
#endforeach
</select>
SearchController.php
function index()
{
$posts = DB::table('posts')
->groupBy('title')
->get();
return view('posts.search')->with('posts', $posts);
}
Does anyone know why i am receiving the error even thoough my posts have been defined.

In your Controller
public function index()
{
$posts = DB::table('posts')
->groupBy('title')
->get();
return view('posts.search',compact('posts'));
}
In your model
#foreach($posts as $distance)
<option value="{{$distance->id}}">{{ $distance->distance}}</option>
#endforeach

Related

I want to displaying comments for each post

hello I just moved from php native and want to try relationships in laravel, so I want to display a post and each comment and the name of user who comments so that when looped the post has a comment that has a relationship with it.
So this is my HomeController.php :
public function index() {
$posts = Post::all();
$comment = Comment::all();
return view('home', [
'posts' => $posts,
'comments' => $comment
]);
}
My Post.php :
public function comments() {
return $this->hasMany(Comment::class);
}
public function user() {
return $this->belongsTo(User::class);
}
My Comments.php :
public function post() {
return $this->belongsTo(Post::class);
}
public function user() {
return $this->belongsTo(User::class);
}
My User.php :
public function post() {
return $this->hasMany(Post::class);
}
My home.blade.php :
#foreach ($posts as $post)
<div class="box-post">
<p>{{ $post->user->name }}</p>
<p>{{ $post->post_content}}</p>
<button>Comment</button>
</div>
#foreach ($comments as $comment)
<div class="box-post">{{ $comment->comment_content }} </div>
#endforeach
#endforeach
the code above runs with the post displayed along with the author but all the comments also appear in all posts, I have searched for references and tried to change the comments value in Controller but the results are still the same so I made the comments appear in each post *$comment = Comment::all();.
what I want is to display posts and comments that relate to each post, like a twitter feature that can reply to people's tweets.
Thx you..
Your relations builded well, so just can simply use $post->comments can get all comments related on each post.
#foreach ($posts as $post)
<div class="box-post">
<p>{{ $post->user->name }}</p>
<p>{{ $post->post_content}}</p>
<button>Comment</button>
</div>
#foreach ($post->comments as $comment) // make changes here
<div class="box-post">{{ $comment->comment_content }} </div>
#endforeach
#endforeach
public function index() {
$posts = Post::with('comments')->get();
return view('home', [
'posts' => $posts,
]);
}
then in blade
#foreach ($posts as $post)
<div class="box-post">
<p>{{ $post->user->name }}</p>
<p>{{ $post->post_content}}</p>
<button>Comment</button>
</div>
#foreach ($post->comments as $comment)
<div class="box-post">{{ $comment->comment_content }} </div>
#endforeach
#endforeach
You have done fine job building models and their relationship.
I recommend you change how you call post query.
public function index(Request $request) {
// add eager loading comments for each post and user
$posts = Post::with('comments', 'user')->get();
// eager loading user is needed, cause in blade you call $post->user->name
// calling comments will no longer needed
// return only $posts
return view('home', compact('posts'));
}
And inside your blade, you can call comments from each post, like this.
#foreach ($posts as $post)
<div class="box-post">
<p>{{ $post->user->name }}</p>
<p>{{ $post->post_content}}</p>
<button>Comment</button>
</div>
#foreach ($post->comments as $comment)
<div class="box-post">{{ $comment->comment_content }} </div>
#endforeach
#endforeach
That's it and if you use barryvdh/laravel-debugbar , you will see there are only 3 queries run, each one from table posts, comments and users.
And for comments query and users query, not all rows will be fetched,
only related to fetched posts from the 1st query.
Have fun using Laravel Framework!
Your PHP native knowledge/expertise will be very useful and speed up your learning/mastering process.

Use "where" and "limit" to child in #foreach

I want to display all user's profile into views and they posts. It's pretty simple:
#foreach($profiles as $profile)
{{ $profile->name }}
#foreach($profile->posts as $post)
{{$post->title}}
#endforeach
#endforeach
But I want to display only the latests posts (->orderBy('created_at', 'desc')->limit(4) ) and only accepted posts (->where('accept', 1)). How can I do that?
You already have what you need. You just need to put it all together.
#foreach($profile->posts()->where('accept', 1)->orderBy('created_at', 'desc')->limit(4)->get() as $post)
I would consider creating a query scope on your profile model. That way you can do something like $profile->latestPosts.
Or you can use the relationship to return exactly what you need.
public function latestPosts() {
return $this->posts()->where('accept', 1)->orderBy('created_at', 'desc')->limit(4)->get();
}
Then you could use it as:
#foreach($profile->latestPosts() as $post)
{{$post->title}}
#endforeach
A better solution would be to lazy load the posts you need when loading the profiles in the controller.
$profile = Profile::with(['posts' => function ($post) {
$post->where('accept', 1)->orderBy('created_at', 'desc')->limit(4);
}])->limit(10)->get();
then in the blade you can do the same as before
#foreach($profiles as $profile)
{{ $profile->name }}
#foreach($profile->posts as $post)
{{$post->title}}
#endforeach
#endforeach
if you want to use a scope for latestAccepted, you can on the Post model
class Post extends Model
{
public function scopeLatestAccepted($query)
{
return $query->where('accept', 1)->orderBy('created_at', 'desc')->limit(4)
}
}
Then lazy load it
$profile = Profile::with(['posts' => function ($post) {
$post->latestAccepted();
}])->limit(10)->get();
what you have to do is pretty simple.
create table users
create table post
create a relationships between the 2 tables
write you code in controller to join the table and query all the users post based on his/her username or password
see sample screenshot for table relationships
//Controller
Public function ViewPost(){
$data['data']=DB::table('useratable')
->where('useratable.username','=', $uname)
->where('useratable.password','<=',$pwd)
->leftjoin('posttable', 'useratable.idusertable', '=', 'posttable.userid')
->orderby('posttable.idposttable','desc')
->get();
}
//Route
Route::get('/view-post','YourController#ViewPost')
//view
#foreach($data as $r)
{{ $r->fullname}} <br>
{{ $r->email}} <br>
{{ $r->topic }} <br>
{{ $r->content }} <br>
{{ $r->datetime}} <br>
...
#endforeach
You need some codes like it on controller:
$profiles = Profile::with(['posts' => function ($query) {
$query->where('accept', 1)
->orderBy('created_at', 'desc');
}])->get();
And add this one to blade file:
#foreach($profiles as $profile)
{{ $profile->name }}
#foreach($profile->posts as $post)
{{$post->title}}
#if ($loop->iteration == 4)
#break
#endif
#endforeach
#endforeach

How to redirect one category to sub category?

This is FrontController
public function index(){
$categories = DB::table('categories')
->select('category')
->groupBy('category')
->get();
return view('front', compact('categories'));
}
This is blade layout
#foreach($categories as $category)
<h2 class="card-title">{{$category->category}}</br></h2>
#endforeach
My question is when i click any category redirect to related to subcategory...How can i do that??
In your controller, you can do the following:
// for categories
public function index() {
$categories = DB::table('categories')
->select('category')
->groupBy('category')
->get();
return view('front', compact('categories'));
}
// for sub categories
public function subCategory($category) {
$sub_categories = DB::table('categories')
->where('category', $category)
->get();
return view('another_front', compact('sub_categories'));
}
In your blade:
// for category
#foreach($categories as $category)
<h2 class="card-title">{{$category->category}}</br></h2>
#endforeach
// for sub category
#foreach($sub_categories as $subcategory)
<h2 class="card-title">{{$subcategory->sub_category}}</br></h2>
#endforeach
And the Route is:
Route::get('/subcategory/{category}', 'FrontController#subCategory');
Can you try this
This is route file "web.php"
project_url /category/{catid}
This is blade layout
#foreach($categories as $category)
<h2 class="card-title">{{$category->category}}</br></h2>
#endforeach

Laravel: Undefined variable after a post action

I'm making profile edit page and I had a problem after post action.
Routes file is
Route::get('profile', 'ProfileController#profile')->name('profile');
Route::post('profile', 'ProfileController#update');
Profile page Controller
public function profile()
{
$cities = City::all();
$current_city = Auth::user()->city;
$current_city_name = City::cityName($current_city);
return view('profile.edit', compact('cities', 'current_city', 'current_city_name'));
}
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|string|email|max:255',
]);
}
public function update(Request $request)
{
$this->validator($request->all())->validate();
$user = Auth::user();
$user->email = $request->input('email');
$user->city = $request->input('city');
$user->save();
$request->session()->flash('message', 'Information successfully changed');
return view('profile.edit');
}
And finally blade template code
<select name="city" id="city" class="form-control">
<option value="{{ $current_city }}">{{ $current_city_name }}</option>
#foreach ($cities as $city)
<option value="{{ $city->id }}">{{ $city->name }}</option>
#endforeach
</select>
First entrance on profile page is ok. But after form submitting I have an error
Undefined variable: current_city (View: C:\OSPanel\domains\ang\laravel\resources\views\profile\edit.blade.php)
You're not passing any variables to the view in your update() method, but returning the same view (that expects those variables) here:
public function update(Request $request)
{
// ...
return view('profile.edit');
}
You could simply redirect back:
public function update(Request $request)
{
// ...
return back();
}

Fetching all users in laravel 5.2

I am trying to fetch all the users in my application so as to pick the user name or id in a select form, but I have not been able to achieve this after a long struggle. My MessageController that retrieves the messages is:
public function getMail(){
$message = Message::orderBy('created_at', 'desc')->get();
$pple = User::where('id', '!=', Auth::id())->pluck('name', 'id')->all();
var_dump($pple);
return view('mail', array('user' => $pple))->with('messages', $message, 'users',$pple );
}
My view that I want to render the users is:
<div>
<select id="recipient">
<option>{{$pple->name}}</option>
</select>
</div>
I have really tried doing this to help me pick up a user id or name to use in my messaging system.I would appreciate if someone helped me with this
You should get your users then pluck to get the result:
$messages = Message::orderBy('created_at', 'desc')->get();
$users = User::where('id', '!=', Auth::id())->pluck('name', 'id');
and return
return view('mail')->with(compact('messages', 'users'));
Then use it this way in your view
<select name="recipient" id="recipient">
#foreach($users as $id => $name)
<option value="{{ $id }}">{{ $name }}</option>
#enforeach
</select>
Don't forget to add a name to your select.
In your view, this should work
#foreach($pple as $userId => $userName)
<option value="{{ $userId }}">{{ $userName }}</option>
#endforeach

Resources