Laravel : Search with posted parameters - php

I am new to Laravel so please be patient with me.
i have to implement search functionality in Laravel. i am able to send form data to the search controller and receiving it as well
public function search_results(Request $request){
if ($request->has('gender')) {
echo $request->gender;
}
.....
}
Now when i am following tutorials on the web i am getting such examples :
public function filter(Request $request, User $user)
{
// Search for a user based on their name.
if ($request->has('name')) {
$user->where('name', $request->input('name'))->get();
}
}
or
public function index()
{
$users = User::where('status', 1)
->where('is_banned', 0)
->get(['name']);
dd($users);
}
now i am not sure from where this User:: or User $user is being added, and what should i do in my scenario.
Your suggestions would be helpful ..
Thanks

The $user represents an object belonging to the model(User::) associated with a table(users) in the mvc structure. If you want to "Search for a user based on their name." That means you already have a users table in database , and a User model .
You can use eloquent queries to retrieve data from database.
A User.php file should be generated when you create a new laravel project with composer. You can check for that.
So when you declare a variable like this :
$user = User::first();
You are actually getting the first element in 'users' table by using your User model.
If you can configure your User model and users table correctly , you should be able to get all records from your users table like this :
$users = User::all();
Then you can filter it like :
$users = $users->where('gender','male') // where('gender',$request->gender) in your situation
If you dont have a users table or a model , you can look to the document about how to create models using artisan commands Laravel API Doc. Generating Model Classes

Related

Trying to get data via related table in Laravel

What I'm trying to do is to show the posts that have been saved by the user in the profile. I will try to explain it as good as possible refering to my code. So:
public function userProfil($id)
I have the profile function which get the data from userprofile table. and inside I have the following code for saved data:
$authed = User::find($id);
$savedarticles = $authed->mysaves;
$allsavings = DB::select("Select * from article where id=$savedarticles->id");
But this code does not work like this anyway. I can do this instead:
$authed = User::find($id);
$savedarticles = $authed->mysaves;
But when I try to get articles from article table with the article_id of mysaves, it does not work such as this:
$allsaved= DB::table('article')->where('id', $savedarticles->article_id);
the error it gives is like:
Property [article_id] does not exist on this collection instance.
although savearticle table has article_id I can output it without the line above and in view I get them as:
#foreach($savedarticles as $savedarticle)
<p>{{$savedarticle}}</p>
#endforeach
it gives me everything that is in the savearticle table and I can get do savedarticle->article_id and get article_id but can't get it in controller.
I am using Laravel 5.4.
The error message Property [article_id] does not exist on this collection instance. means you are trying to get an attribute of a single instance but from a collection.
For example the collection could be like
[$article1, $article2, $article3]
therefore what you tried to do is something similar to
[$article1, $article2, $article3]->article_id
You are trying to get an attribute from a collection instead of a single instance.
As for your query, you can use where in sql statement to search for rows that match any item in an array
$allsaved= DB::table('article')->whereIn('id', $savedarticles->pluck('article_id')->all());
What I have understood is that A USER has many POSTS and a POST belong to an article.
If this is true then you have to do following.
1: In USER model define a relation to get all posts. like below.
public function posts() {
// Foreign key will be a key that is stored in posts table and represent the user MAY BE: user_id
$this->hasMany(Posts::class, 'foreign_key', 'local_key')
}
This will allow you to get all posts belong to a user.
2: In posts, model defines a user relation like below.
public function user() {
$this->belongsTo(User::class, 'foreign_key', 'local_key');
}
This will allow you to get a post User;
3: Now in your controller you will have something like this.
public function show($user_id) {
// find a user with posts as eager loading(to avoid query again)
$user = User::with(['posts'])->where('id', $user_id)->first();
// get all posts that belong to this user
$posts = $user->posts;
}
In controller show($user_id) method you will have a user data as well as user posts data. Now if you want to get a post relations then simply define as below. let say a post belongs to an article as well.
4: In posts, model defines a relation to get an article.
public function article() {
// This will allow you to get a post artcle
$this->belongsTo(Article::class, 'foreign_key', 'local_key');
}
Now you can get the article as well while finding a user. please see below. I am rewriting controller show action to give you a better understanding.
5: Get a user with user_id
public function show($user_id) {
// find a user with posts as eager loading(to avoid query again)
// eager loading for posts & post child, this will give you NOSQL at runtime and all data will come from one query.
$user = User::with(['posts', 'posts.article'])->where('id', $user_id)->first();
// get all posts that belong to this user
$posts = $user->posts;
foreach($posts as $post) {
$article = $post->article; // Child relation of post.
}
}
Hope you will understand the flow, you have to make sure models relation to work it perfectly. If you need further help please let me know.

How to store auth::user profile data into Laravel view?

I work on a project to learn Laravel.
So, I create a database with users. Each user got a profile with information like: city,country,etc.
I create a table named 'profiles' where I have the following columns: id / user_id / country / city.
My routes file looks like:
Route::get('editProfile', 'ProfileController#editProfileForm');
My ProfileController looks like:
public function editProfileForm() {
return view('profile.editProfile')->with('data', Auth::user()->profile);
}
And when I call the view as: {{ $data }}in editProfile.blade, it should return the authenticate user data from database and also I need the row form 'profiles' table where my user_id corresponds to id form 'users' table.
The problem is that my view returns an empty string, not what I expect form the database.
Why is users and profiles two separate tables?
I solve it.
This is how I do it:
In ProfileController I made the following function:
public function editProfileForm() {
$userData = DB::table('users')
->leftJoin('profiles', 'profiles.user_id','users.id')
->where('users.id',Auth::user()->id)
->get();
return view('profile.editProfile')->with('userData', $userData);
}
And that's how I got my info from db in $userData var. And I can display on inputs my data like {{$userData->city}} as an example.
Thanks to all !

Laravel blade multiple select. How to select records in the pivot table?

I am using Laravel, and I have a projects table and a users table. Each project can have multiple users. I have set up a project_user pivot table.
I am trying to create a multiselect box that lists all users, and has the users currently assigned to the project selected. Here is my ProjectsController function that creates the view.
public function edit($id)
{
$project = Project::findOrFail($id);
$users = User::lists('name','id');
return View::make('projects.edit', compact('project','users'));
}
And here is the relevant blade form:
{{ Form::select('user_id[]', $users, ??? , array('multiple')) }}
Where I think ??? should be an array of user_ids associated with the project. Can I get that from
$project->user...something here?
Or, do I need to create the array in function edit()?
You are almost there. First make sure you have the correct relationship defined in your project model
public function users(){
return $this->belongsToMany('User');
}
Now to get the ids of all assigned users:
$assignedUserIds = $project->users()->lists('id');
And just pass that to the view...
Accepted answer is right except on Laravel 5.2 I had to do ->toArray():
$assignedUserIds = $project->users()->lists('id')->toArray();
to get this to work with Form::select.
I would have commented original answer, but I don't have enough reputation.
$assignedUserIds = $project->users()->lists('id');
to
// I used in laravel 5.7
$assignedUserIds = $project->users()->pluck('id');

model with user id laravel

I am developing an application where I want to get all of a user's open tasks and display them. I have created a new view, route, controller and model, but I can't get the model to work right, especially as it pertains to getting the current user's ID for the SQL query.
app/models/Task.php
class Task extends Eloquent
{
public static function open()
{
$id = Auth::user()->id;
$tasks = DB::table('tasks')->where('c', 0)->where('user_id', $id)->get();
return $tasks;
}
}
Also
app/controllers/TaskController.php
public function open()
{
$tasks = Task::open();
return View::make('tasks.open')->with('tasks', $tasks);
}
Error: Trying to get property of non-object - looks like on the $id = Auth::user()->id;
What's the correct model?
Looks like not being logged in was the problem - this model works.
Because this will probably help someone else in the future: when you create a user's account, use Hash::make when you add the password to the database, because when you use Auth::attempt in your log in method, Laravel hashes password the user typed and compares the two, and if they're both not hashed, it won't log the user in.

Eloquent where owner equals follow

I am trying to make a twitter like feed in an application, I have a database called connections where inside there's user and follow and another database called feed containing owner which would equal to the follow column in connections.
What I could do if had every id of a follower statically is to use where('owner', '=' $follow) on each follower and return it.
I tried this approach but it wasn't ideal:
Get each follower inside connections;
foreach(follower) {
Get 10 of the latest posts orderBy "created_at";
Push into array;
}
shuffle array;
limit array to 15;
return array;
That also ended with the returned array not being ordered by created date.
How would I use eloquent to get the feed item only if the user follows the owner in the best/simplest way?
Are there any specific Laravel tools that can be used?
Also the database layout isn't fixed as it is, it can be altered if needed to better suite this.
You need to create a many-to-many relationship between the user and itself. See the laravel eloquent documentation http://laravel.com/docs/eloquent#relationships. I didn't test this code but it should be enough to get you started down the right track.
Create a pivot table called "user_following" with:
(int) id, (int) user_id, (int) following_id
Then do something like this:
<?php
// Model
class User extends Eloquent {
public function following()
{
return $this->belongsToMany('User', 'user_following', 'user_id', 'following_id');
}
public function tweets()
{
return $this->hasMany('Tweet')->orderBy('created_at', 'desc');
}
}
// controller
$tweetsOfWhoImFollowing = User::find($id)->following->tweets;

Categories