Find user by name and surname in USER collection - laravel

This is my code:
public function search_clients($names){
$user = Auth::user();
$all_clients = $user->clients; // Retrieve object of all clients of user
$names = ["Pera","Peric"]; // Pera - name, Peric - surname
$collect = collect($all_clients);
$klijenti = $collect->filter(function($query) use ($names){
$query->whereIn('name', $names);
$query->orWhere(function($query) use ($names) {
$query->whereIn('surname', $names);
});
return $query;
});
return $klijenti;
}
I want to search in object for name and surname and return it. Like if I have 100 users in $all_clients, i want to return only users name or surname LIKE "PERA" or "PERIC".
Currently it is returning everyone.

An option would be to define a search scope on the Client model
class Client extends Model
{
public function scopeSearch($query, $searchTerm)
{
$query->where("name", "ilike", "%$searchTerm%")
->orWhere("surname", "ilike", "%$searchTerm%");
}
//rest of the code
}
Then in the controller method you can use the scope
public function search_clients($names)
{
$user = auth()->user();
$all_clients = $user->clients()->search($names)->get();
return $all_clients;
}

Related

Count the number of posts for logged in user in laravel

I want a number of posts that logged in user to have
I tried but I don't know how it will work
public function limitation()
{
$limit = 3;
$ads = User::WithCount('ads')->get();
}
Any help will appericiate
it works!!
$limit = 3;
$userId = auth()->user()->id;
$userPostCountId = User::where('id', $userId);
$posts=User::withCount('ads')->first(); //Suggest:- it will return post counts
along with user details
if ($userId>0) {
# code...
if(isset($posts->ads))
{
$count = sizeof($posts->ads);
if ($count>=$limit) {
return redirect()->route('ad.index');
}
}
If you have set up your user-posts relationship correctly like so:
class User {
public function posts(){
return $this->hasMany('App\Posts')
}
}
then you can get the users posts like so
$user = Auth::user();
$numPosts = $user->posts()->count();
Read more about relationships and how to query them here: https://laravel.com/docs/6.x/eloquent-relationships#one-to-many
Make sure you defined proper model naming
Also, you have to define a relationship between users and posts
User Model
public function posts()
{
return $this->hasMany(Posts::class);
}
In your controller
public function userPosts()
{
$userId = auth()->user()->id;
$userPostCount = User::where('id', $userId)->withCount('posts')->first(); //Suggest:- it will return post counts along with user details
//or auth()->user()->posts()->count() //it will return only post count
// or if you want to count with post also
// $userPosts = User::where('id', $userId)->with('posts')->withCount('posts')->first(); // it will return user posts and post counts along with user data
return $userPostCount; // or $userPosts
}
For more information please read: Laravel eloquent relationship
use skip and take functions
$limit = 3;
$ads = User::WithCount('ads')->skip(0)->take($limit)->get();

why i can't call name from table food?

public function orderlist(Request $request){
$id = $request->id;
$data['order'] = Order::where('shop_id',$id)->orderBy('id')->get();
foreach($data['order'] as $orders){
$orders->shop = Shop::where('id',$orders->shop_id)->first();
$orders->food = Food::where('id',$orders->food_id)->get();
}
return $orders->food->name;
return view ('administrator.users.list_order.index',$data);
}
If you set up proper Eloquent relationships, this code could be rewritten like so:
public function orderlist(Request $request, Shop $shop){
$orders = $shop->orders()->with(['food'])->get();
return view ('administrator.users.list_order.index',compact('orders'));
}
Check out the docs here: https://laravel.com/docs/5.7/eloquent-relationships

how to view order submitted by customer to the seller?

A customer can post an order to the seller. The problem is how can seller(ps) can view his order.Because each order may be submitted to different seller.
SLotController.php
public function order(Request $request)
{
$slotorder = new Slotorder;
$slotorder->name = $request->name;
$slotorder->user_name = Auth::user()->name;
$slotorder->user_id = Auth::user()->id;
$slotorder->type = $request->type;
$slotorder->quantity = $request->quantity;
$slotorder->size = $request->size;
$slotorder->ps_id = ? // i dont know how to get seller id
$slotorder->save();
return view('home');
}
User model
public function slotorder()
{
return $this->hasMany('Slotorder::class');
}
SlotOrder model
public function user()
{
return $this->belongsTo('User::class');
}
public function user()
{
return $this->belongsTo('Ps::class');
}
Ps Model
public function slotorder()
{
return $this->hasMany('Slotorder::class');
}
Update
After user click make an order, it will go to this page according to their id. For this screenshot the id for the seller is 1. So back to my question , how can i get the seller id when user submit the order. Therefore he can view the order in his dashboard.
You are using a get route, which uses the seller id, so in the method which handles this route send the variable to the view, example:
Route
Route::get('giveorder/{seller_id}',Controller#method);
Controller Method
public function method($seller_id){
return view('giveorder',compact('seller_id'));
}
Create a hidden input inside your form:
<input type="hidden" value="{{$seller_id}}" name="seller_id">
So now you can use this seller_id in your order method:
public function order(Request $request)
{
$slotorder = new Slotorder;
$slotorder->name = $request->name;
$slotorder->user_name = Auth::user()->name;
$slotorder->user_id = Auth::user()->id;
$slotorder->type = $request->type;
$slotorder->quantity = $request->quantity;
$slotorder->size = $request->size;
$slotorder->ps_id = $request->seller_id;
$slotorder->save();
return view('home');
}

Adding custom eloquent attribute in Laravel 5

I have a function named siblings which fetches all siblings of a user.
select siblings(id) as `siblings` from users where id = 1
I can access the function in Eloquent as
User::where('id', 1)->first([DB::raw(siblings(id) as `siblings`)]->siblings;
I want to make the siblings available via custom attribute.
I added siblings to $appends array
I also created getSiblingsAttribute method in my User model as
public function getSiblingsAttribute()
{
if (!$this->exists()) {
return [];
}
$siblings = User::where('idd', $this->id)
->first([DB::raw('siblings(id) AS `siblings`')])
->siblings;
return explode(',', $siblings);
}
But this is not working as $this->id returns null
My table schema is users(id, username,...), so clearly id is present.
Is there a way by which I can bind the siblings function while querying db and then returning something like $this->siblings from getSiblingsAttribute. If I can bind siblings(id) as siblings with query select globally as we do for scopes using global scope.
That way my code can be simply
public function getSiblingsAttribute()
{
return $this->siblings;
}
The simplest way is to create a view in your database and use that as a table:
protected $table = 'user_view';
Otherwise I need more information about your id == null problem.
If you can fix this by your own in the next step it is important that you use an other column name by selecting as in your accessor otherwise you run in an infinite loop.
public function getSiblingsAttribute()
{
if (!$this->exists()) {
return [];
}
$siblings = User::where('id', $this->id)
->first([DB::raw('siblings(id) AS `siblings_value`')])
->siblings_value;
return explode(',', $siblings);
}
EDIT
Sadly there is no simple way to archieve this.
But after a little bit tinkering I have found a (not very nice) solution.
Give it a try.
You have to add the following class and trait to your app.
app/Classes/AdditionalColumnsTrait.php (additional column trait)
namespace App\Classes;
trait AdditionalColumnsTrait {
public function newEloquentBuilder($query) {
$builder = new EloquentBuilder($query);
$builder->additionalColumns = $this->getAdditionalColumns();
return $builder;
}
protected function getAdditionalColumns() {
return [];
}
}
app/Classes/EloquentBuilder.php (extended EloquentBuilder)
namespace App\Classes;
use Illuminate\Database\Eloquent\Builder;
class EloquentBuilder extends Builder {
public $additionalColumns = [];
public function getModels($columns = ['*']) {
$oldColumns = is_null($this->query->columns) ? [] : $this->query->columns;
$withTablePrefix = $this->getModel()->getTable() . '.*';
if (in_array('*', $columns) && !in_array($withTablePrefix, $oldColumns)) {
$this->query->addSelect(array_merge($columns, array_values($this->additionalColumns)));
} elseif (in_array($withTablePrefix, $oldColumns)) {
$this->query->addSelect(array_values($this->additionalColumns));
} else {
foreach ($this->additionalColumns as $name => $additionalColumn) {
if (!is_string($name)) {
$name = $additionalColumn;
}
if (in_array($name, $columns)) {
if (($key = array_search($name, $columns)) !== false) {
unset($columns[$key]);
}
$this->query->addSelect($additionalColumn);
}
}
if (is_null($oldColumns)) {
$this->query->addSelect($columns);
}
}
return parent::getModels($columns);
}
}
after that you can edit your model like this:
class User extends Model {
...
use App\Classes\AdditionalColumnsTrait;
protected function getAdditionalColumns() {
return [
'siblings' => DB::raw(siblings(id) as siblings)),
];
}
...
}
now your siblings column will be selected by default.
Also you have the option to select only specific columns.
If you don't want to select the additional columns you can use: User::find(['users.*']).
Perhaps it is a solution for you.

Laravel profile edit

Alright , I have used this way to save the users info and It works perfect,
static public function memberSave($request) {
$signup = false;
$member = new Members();
$member->name = $request['name'];
$member->email = $request['email'];
$member->password = bcrypt($request['password']);
$member->save();
if (!empty($member->id)) {
$new_id = $member->id;
DB::insert("INSERT INTO roles VALUES ($new_id, 5613)");
$signup = true;
Session::flash('sm', 'Thank you! You have signed up successfully!');
}
return $signup;
}
but when making this for editing the profile(by user) It doesn't work
becuase I use new(); (making object)
I also didn't succeed to use find(); so I tried to use this
static public function saveProfile($id,$name,$email,$password) {
$sql = "UPDATE members SET name=?,email=?,password=? WHERE id=?";
$member = DB::select($sql, [$name,$email,$password,$id]);
but when I want to bcrypt the password in laravel doesnt work .
this is the code also in the second page
public function postProfile(ProfileValidation $request) {
if (Members::saveProfile($request['id'], $request['name'], $request['email'], $request['password'])) {
return redirect('');
}
}
I hope getting helped for editing the users profile by laravel , thanks.
Your Members class must extend Eloquent\Model for following this code to work.
class Members extends Model {
// optional
protected $table = 'members';
...
To find and update the member using email,
// find the single member
$member = Members::where('email', request['email'])->first();
// update the member
$member->name = $request['name'];
$member->password = $request['password'];
// now save the updated member
$member->save();
In order to to encrypt Password, Laravel provides Hash Facade,
// import this
use Hash;
...
// encrypt Password
$encrypted = Hash::make($request['password']);
...
if you want your user automatically hash the password at your model put:
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
and you can directly check for the user if exist create new or update it:
public function saveMember($request)
{
$member = Member::findOrNew($request->email);
//All your input you want to save
$member->save();
}

Resources