Return Logged User's Posts Into laravelcollective/html Select Dropdown Menu Within a Form - laravel

I am trying to pass only the posts created by the logged in user into a laravelcollective/html select drop down menu within a form.
In my code I have two examples. Using the variable example shows how I can get the dropdown select menu to show all results from the posts table. Using the variable posts in a foreach loop shows how I can return just the posts created by the logged user, but not in a select menu.
I need to have the dropdown menu function as in the form using example but displaying results of the foreach posts loop.
Controller
public function createPost()
{
$example = Post::pluck('title', 'id')->all();
$posts = Posts::all();
return view('post.create', compact('posts', 'example'));
}
Example View
<div class="form-group">
{!! Form::label('example', 'Posts:') !!}
{!! Form::select('example', ['' => 'Select'] + $example, null) !!}
</div>
Foreach Loop Posts View
#foreach($posts as $post)
#if(Auth::user()->id == $post->user_id)
{{ $post->title }} <br>
#endif
#endforeach

try $posts = Posts::where('user_id',\Auth::id())->get()->pluck('title','');. It will return only posts of logged in user.
{{ Form::select('example', $posts) }}
You are using select box wrong.
#foreach($posts as $post)
#if(Auth::user()->id == $post->user_id)
{{ $post->title }} <br>
#endif
#endforeach

I would update your controller to only return posts by the user rather than rely on the foreach check if Auth::user()->id == $post->user_id
public function createPost()
{
$posts = Posts::where('user_id', auth()->user()->id)->get();
return view('post.create', compact('posts'));
}
As a side note, your method should probably just be create() to keep inline with the standard CRUD.
Then in your blade,
<div class="form-group">
{!! Form::label('post', 'Posts:') !!}
{!! Form::select('post', ['' => 'Select'] + $posts, null) !!}
</div>

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.

Issues with search query

I am trying to run a search query on all of my comments. I am encountering a number of problems. I would to have two search queries one that runs a search on the comment ID and another that runs a search on the username that is connected to the comment through the user_id FK.
Currently im getting the problem:
Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in
Tables:
Comment- id, comment, user_id, timestamps
User - id, name, username
Models:
class Comment extends Model
{
public function author()
{
return $this->belongsTo('App\User','user_id');
}
}
Controller:
public function index(Request $request)
{
$comment =Comment::paginate(10);
$id=$request->input('id');
$name=$request->input('username');
if(!empty($id)){
$comment->where('id', $request->input('id') )->get();
}
if(!empty($name)){
$comment->where($comment->author->username, 'LIKE', '%'.$name.'%')->get();
}
return view('comments.index')->withComment($comment);
}
View:
<div class="panel-body">
{!! Form::open(['route' => 'comments.index', 'method' => 'GET']) !!}
<div class="col-md-5">
{!! Form::label('id', 'Search By ID:') !!}
{!! Form::text('id', null, array('class' => 'form-control')) !!}
</div>
<div class="col-md-5">
{!! Form::label('username', 'Search By Username:') !!}
{!! Form::text('username', null, array('class' => 'form-control')) !!}
</div>
<div class="col-md-2">
{!! Form::submit('Find Comments', array('class' => 'btn btn-send ')) !!}
</div>
{!!Form::close()!!}
</div>
#foreach($comment as $comments)
//data
#endforeach
The paginate function immediately executes the query for you, so you are using Collection functions after that. The get function on collections expects a key as a parameter, this is the problem.
To fix this, you can either remove the ->get() or use the paginate function at the end of your query as shown below.
$comment = Comment::query();
$id = $request->input('id');
$name = $request->input('username');
if (!empty($id)) {
$comment = $comment->where('id', $request->input('id'));
}
$result = $comment->paginate(10);
Since You have Paginated already
public function index(Request $request)
{
$comment = new Comment();
$id=$request->input('id');
$name=$request->input('username');
if(!empty($id)){
$comment->where('id', $request->input('id') )->get();
}
if(!empty($name)){
$comment->where($comment->author->username, 'LIKE', '%'.$name.'%');
}
return view('comments.index')->withComment($comment->paginate(10));
}
You cannot paginate and get it again, its like using SELECT statement twice on same object.

how to display dynamic value without using foreach loop in laravel

How to print these type of data in laravel.I am trying to create dynamic menu and these type of problem occurs.Code is like this. my code is like this.
In view composer.
public function compose(View $view)
{
$menus = $this->menu->getDynamicMenus();
$user_role = $this->role->lists('name', 'id');
//dd($user_role);
$view->with('user_role', $user_role)->with('menus', $menus);
}
menurepository code.
public function getDynamicMenus()
{
$user = $this->auth->user();
$roles = $user->roles;
// dd($roles);
$menus = [];
foreach ($roles as $role) {
//dd($role);
foreach ($role->menus as $menu) {
if ($menu["parent_id"] > 0) {
$menus[$menu["parent_id"]][$menu["id"]] = $menu->toArray();
} else {
$menus[$menu["id"]] = $menu->toArray();
}
}
}
// dd($menus);
return $menus;
}
and i print in frontend like.
#foreach($menus as $menu)
{{-- {!! Form::open() !!}
{!! Form::select('menus',$menus) !!}
{!! Form::close() !!}--}}
{{--{!! $menuitem->menu_name !!}--}}
{!! $menu->menu_url !!}
#endforeach
and it shows problem:
Trying to get property of non-object (View: E:\xampp\htdocs\basicwc\resources\views\layouts\partials\sidebar.blade.php) (View: E:\xampp\htdocs\basicwc\resources\views\layouts\partials\sidebar.blade.php) (View: E:\xampp\htdocs\basicwc\resources\views\layouts\partials\sidebar.blade.php)
as menu are getting in array like in image.
any help??
i tried to do like:
{!! menu($menus) !!}
but it says undefined problem.
I added another menu and it's structure is like this:
Access it like an array:
#foreach($menus as $menu)
...
{{ $menu['menu_name'] }}
{{ $menu['menu_url'] }}
#endforeach

Don't show the URL's parameters in Laravel 4.1

I have a CRUD for Users in Laravel 4.1
When the user want see his data, the url is: mydomain.com/public/users/3 (the show method).
How I can hide the id "3" in the url? So, if the number is visible, the user can see the data of other users (as 4,5 or others id)?
Thanks
In my filter.php I have:
Route::group(array('before' => 'auth'), function()
{
Route::resource('users', 'UserController');
});
Finally solved.
In UserController.php:
public function show()
{
//
$usuario = Auth::user();
// show the view and pass the nerd to it
return View::make('users.show')
->with('elusuario', $usuario);
}
In show.blade.php
#extends ("layout/layout")
#section ("principal")
<div class="form-group">
{{ Form::label('nombre', 'Nombre') }}
{{ Form::text('nombre',null, array('class' => 'form-control','placeholder'=>$elusuario->nombre,'disabled'=>'disabled')) }}
</div>
<div class="form-group">
{{ Form::label('email', 'Email') }}
{{ Form::email('email',null, array('class' => 'form-control','placeholder'=>$elusuario->email,'disabled'=>'disabled')) }}
</div>
<a class="btn btn-success" href="{{ URL::to('users/' . $elusuario->id . '/edit') }}">Modificar datos</a>
#stop
That solved the issue and the url don't show the id of user. Simply called as mydomain.com/public/users/perfil and has the data (id, name, etc) from session variable.

Laravel pre-filling multiple forms if validation failed

One of the coolest Laravel feature is, Laravel pre-filled the form fields if validation error occurred. However, if a page contain more than one form, and form fields have same name, Laravel pre-filling all forms fields.
For example:
I have a page where i have two forms to create new users or whatever.
<h1>Create user1</h2>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
Controller
class UsersController extends BaseController
{
public function store()
{
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
return Redirect::back()->withInput()->withErrors($validation);
}
}
}
As i didn't fill up the email, Laravel will throw validation error and pre-filling the forms as following:
How to tell Laravel that do not fill-up the second form?
There's no Laravel way of doing this, but you can use HTML basic form arrays to make it work. You need to understand that you have to identify your forms and fields so Laravel knows exactly where the data came from and where to send it back to. If all your fields have the same name how could it possibly know?
This is a proof of concept that will work straight from your routes.php file.
As I did it all and tested here before posting the answer I used Route::get() and Route::post(), to not have to create a controller and a view just to test something I will not use. While developing this you will have to put this logic in a controller and in a view, where I think they are alredy in.
To test it the way it is, you just have to point your browser to the following routes:
http://yourserver/form
and when you push a button it will automatically POST tho the route:
http://yourserver/post
I'm basically giving all forms a number and giving the buttons the number that we will usin in Laravel to get the form data and validate it.
Route::get('form', function()
{
return Form::open(array('url' => URL::to('post'))).
Form::text('form[1][name]', null).
Form::email('form[1][email]', null).
'<button type="submit" name="button" value="1">submit</button>'.
Form::close().
Form::open(array('url' => URL::to('post'))).
Form::text('form[2][name]', null).
Form::email('form[2][email]', null).
'<button type="submit" name="button" value="2">submit</button>'.
Form::close();
});
And here we get the data, select the form and pass all of it to the validator:
Route::post('post', function()
{
$input = Input::all();
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make($input['form'][$input['button']], $rules);
return Redirect::back()->withInput();
});
This is how you use it in a Blade view, now using 3 forms instead of 2 and you can have as many forms as you need:
<h1>Create user1</h2>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[1][name]', null) }}
{{ Form::email('form[1][email]', null) }}
<button type="submit" name="button" value="1">submit</button>
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[2][name]', null) }}
{{ Form::email('form[2][email]', null) }}
<button type="submit" name="button" value="2">submit</button>
{{ Form::close() }}
</h1>Create user3</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[3][name]', null) }}
{{ Form::email('form[3][email]', null) }}
<button type="submit" name="button" value="3">submit</button>
{{ Form::close() }}
And you can even use a loop to create 100 forms in blade:
#for ($i=1; $i <= 100; $i++)
User {{$i}}
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text("form[$i][name]", null) }}
{{ Form::email("form[$i][email]", null) }}
<button type="submit" name="button" value="{{$i}}">submit</button>
{{ Form::close() }}
#endfor
Use old input with $request->flash().
https://laravel.com/docs/5.2/requests#old-input

Resources