Count the number of posts for logged in user in laravel - 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();

Related

Find user by name and surname in USER collection

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;
}

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

laravel many to many with chaining where clause

I have a given table :
tools toolparts parts part_details
----- --------- ----- ------------
id* id* id* id*
name tool_id name part_id
part_id total (int)
----- --------- ----- ------------
the relation between Tools and Parts is ManyToMany. and the relation between parts and part_details is one to many.
with Laravel model, how can I get tool with part that has the biggest part_details.total ??
//tool model
public function parts()
{
return $this->belongsToMany('App\Part', 'tool_part');
}
//part model
public function tools()
{
return $this->belongsToMany('App\Tool', 'tool_part')
}
public function details(){
return $this->hasMany('App\Part_detail');
}
//partDetail model
public function part(){
return $this->belongsTo('App\Part');
}
Controller
public function index()
{
$tools = Tool::with('parts', 'parts.details')->has('parts')->get();
return $tools;
}
what I expected is something like :
Controller
public function index()
{
$tool = Tool::with('SinglePartThatHasHigestTotalInPartDetail');
}
Any Idea ??
You can use Laravel aggregates for querying to get the desired result,
In your code use max() function,
public function index()
{
$tool = Tool::with(['parts.part_details' => function ($query) {
$max = $query->max('total');
$query->where('total',$max);
})->first();
}
I haven't tested this but you can do like this.
Comment if you will get any errors.
I Manage my problem with "hacky" ways. if someone have a better and more elegant solution, please tell me.
//tool model
public function partWithHighestTotalDelivery($trans_date = null){
if (is_null($trans_date)) {
$trans_date = date('Y-m-d');
}
$parts = $this->parts;
$highest_total_delivery = 0;
foreach ($parts as $key => $part) {
$part->detail;
$total_delivery = $part->first_value;
if (isset( $part->detail->total_delivery )) {
$total_delivery += $part->detail->total_delivery;
}
if ($highest_total_delivery < $total_delivery ) {
$highest_total_delivery = $total_delivery;
$part->total_delivery = $highest_total_delivery;
$result = $part;
}
}
if (!isset($result)) {
$result = null;
}
$this->part = $result;
}
In controller i have :
public function index(Request $request){
$tools = Tool::has('parts')
->get();
$tools->each(function($tool){
$tool->partWithHighestTotalDelivery();
});
return $tools;
}
with this, I need to run tool->partWithHighestTotalDelivery() tools.count times. which is take noticeable process if the tools is many.
and also, the code I post and the question I ask has a slightly difference.that's for a simplicity sake's
Use the the hasManyThrough Relationship to get the all part details related to tool and then you can check the one by one record and get the highest total of the tool part.
// Tool Model
public function partsdetails()
{
return $this->hasManyThrough('App\PartDetail', 'App\Part','tool_id','part_id');
}
In Your controller
$data = Tool::all();
$array = [];
if(isset($data) && !empty($data)) {
foreach ($data as $key => $value) {
$array[$value->id] = Tool::find($value->id)->partsdetails()->max('total');
}
}
if(is_array($array) && !empty($array)) {
$maxs = array_keys($array, max($array));
print_r($maxs);// This array return the max total of the tool related parts
}
else{
echo "No Data Available";
}
You can start with the part detail and get the tool(s) from there:
$maxPartDetail = Part_detail::orderByDesc('total')->first();
$tools = $maxPartDetail->part->tools;

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');
}

Laravel - Best way to store user and his/her dynamically created relations on submit

Which way should I store User Relations which are made "Dynamically"?
By that i mean. I have People table with record of husband for example now husband can add as relation to him (hasMany) his wife and children. Now I have setup the model and it works
Model
This relations are in same table as data is same for them I only need to know if they belong to husband
public function children(){
return $this->hasMany( get_class($this) ,'people_id','id');
}
public function parent(){
return $this->belongsTo( get_class($this) , 'people_id','id');
}
Now when i go to form and add a person husband there. I would have an option to dynamically add his children() (his wife, his children, his grandma...) and submit once its done.
Now i have tought about saving these children to Session first (put them in array) and on submit to post it to controller. Is this a good way or should i do it some other way?
(I hope i explained this well, if not i will try to explain it better)
I have done it like this i dont know if this way is ok but it works for me. Also to add i have just used name for the DB data as i wanted to get this to work.
Store parent and his/her children (if any) in DB from Session
public function store(AdminCreatePersonRequest $request)
{
$data = $request->all();
$parent = new Person;
$parent->name = $data['name'];
$parent->save();
$children = $request->session()->pull('children');
if ($children != null) {
foreach($children as $childData){
$child = new Person(['name' => $childData['child-name']]);
$parent->children()->save($child);
}
}
return redirect('dashboard')->with('success', ['The user was successfully created']);
}
AJAX
Add child to session
public function add(AdminCreatePersonChildRequest $request)
{
$temp = $request->session()->get('children',[]);
$data = $request->all();
unset($data['_token']);
array_push($temp,$data);
end($temp);
$key = key($temp);
$data += ['id' => $key];
$request->session()->put('children', $temp);
return $data;
}
Remove child from session
public function delete(Request $request, $id) {
$temp = $request->session()->pull('children');
unset($temp[$id]);
$request->session()->put('children', $temp);
return 1;
}
Load children from Session on view create (if any)
public function load(Request $request) //get children from session (if exists)
{
$data = $request->session()->get('children');
if($data != null){
return $data;
}
else {
return 0;
}
}
Clear all children from session
public function clear(Request $request) //remove children from session
{
$request->session()->forget('children');
return 1;
}
And with data form controller you update your view (in my case add <li> to <ul> element)

Resources