Collection is empty - php

So I'm basically trying to retrieve all "favourites" for a specific user from the pivot table favourite (yes it seems that I started my project by misspelling the word favorite).
So when viewing u/Admin, I should be able to view all games admin has favorited.
public function index(User $user)
{
$favourites = Auth::user()->favourites;
// dd($favourites);
return view('u.index', compact('favourites'));
}
But when dd($favourite);, I'm returned a empty collection.
Collection {#216 ▼
#items: []
}
in m y Users.php i have the following:
public function getRouteKeyName()
{
return 'name';
}
public function favourites()
{
return $this->belongsToMany(Game::class, 'favourites', 'user_id', 'game_slug')->withTimeStamps();
}
Might it have something to do with that Game.php has it route key set to the slug?
public function getRouteKeyName()
{
return 'slug';
}

Try this:
Create a model called 'Favourite'(make sure you have a user_id column in the favourites table)
put this in your controller -> use App\Favourite;
And try this code:
$user_id = Auth::user()->id;
$favourites = Favourite::where('user_id', $user_id)->get();

Related

How to get query of users in Laravel with where condition

I have a table for users and in that table, I have the column user_type_id which is related to another table called user_types. There are specific roles(subscriber and admin). Now, In my controller, I want to get all users with the condition that their user_type_id is equal to 2. With this way of doing it, I am getting only the first row...
My Controller:
public function show($id)
{
$subscriber = User::where('user_type_id', 2)->firstOrFail();
return view('show_subscriber', compact('subscriber'));
}
public function show($id) {
$subscriber = User::where('user_type_id', 2)->get();
return view('show_subscriber', compact('subscriber'));
}
public function show($id) {
$subscriber = User::where('user_type_id', 2)->firstOrFail();
return view('show_subscriber', compact('subscriber'));
}
firstOrFail() will return the first matching record and if no matching record is found it will simply return 404- resource not found.
public function show($id) {
$subscriber = User::where('user_type_id', 2)->get();
return view('show_subscriber', compact('subscriber'));
}
get() will return all the matching records as a collection.
see details here https://laravel.com/docs/9.x/eloquent#not-found-exceptions.
https://laravel.com/docs/9.x/eloquent#collections

How to get a custom collection based on a data that is most repeated (from top to bottom))

I have a table like this:
Basically this table is named favourite_products and contains product ids that are added as favourite for users.
Now I wanted to get a collection of most added product from this table.
So in this case, a product with an id of 10 would be on top of the collection.
But I don't know how to get this collection ordering by from most repeated product id (prd_id)...
Here is the Model:
class FavouriteProduct extends Model
{
protected $table = 'favourite_products';
protected $fillable = ['usr_id','prd_id'];
public function user()
{
return $this->belongsTo(User::class, 'usr_id');
}
public function product()
{
return $this->belongsTo(Product::class, 'prd_id');
}
}
UPDATE #1:
Product.php Model:
public function favouritees()
{
return $this->belongsToMany(User::class, 'favourite_products', 'prd_id', 'usr_id');
}
I think the following code solve your problem:
$most_liked_products = DB::table('favourite_products')
->select(DB::raw('count(prd_id) as total'), id)
->groupBy('total')
->orderByDesc('total')
->get();
Please try it and give your feedback
try use this
public function example()
{
$data=FavouriteProduct::orderBy('prd_id', 'ASC')->get();
dd($data);
}

Laravel 5.2 trying to get user_id post

I am following a Laravel course on Udemy and while I followed everything the instructor did, for some weird reason I am not getting the expected result.
This is the Relationship One to One lesson and I added a function in User Model to check if it has any posts.
Then added the route to display post if user_id equals.
app\User.php
public function post() {
return $this->hasOne('App\Post');
}
app\Http\routes.php
Route::get('/user/{id}/post', function($id) {
return User::find($id)->post;
});
Below is the screenshot from the database showing that I have a post with user_id = 1 in the posts table. I also have a user with id=1 in the user's table.
MySQL data
Why do I get a blank page when visiting domain/user/1/post?
Sohel, i got a result from your function, but had to use
var_dump(User::with('post')->where('id',1)->first());
Then tried something else:
return User::with('post')->where('id',$id)->first();
And this is the result:
{"id":1,"name":"Nick","email":"nick#kriogen.name","created_at":"2018-03-15 09:49:51","updated_at":"2018-03-15 09:49:51","post":null}
Your one to one relationship should go as:
app\User.php
public function post() {
return $this->hasOne('App\Post');
}
app\Post.php
public function user() {
return $this->hasOne('App\User');
}
you can try doing this function in controller:
public function getPost {
$user= User::find($id);
return $user->post();
}
The issue was not with the functions, the issue was in the database.
Column deleted_at was not NULL and it was marking the post as being soft deleted, therefore not being displayed.
Since the "user_id" field is in the "posts" table, the relation in the App\User model need to be:
public function post() {
return $this->hasMany('App\Post');
}
then, call it without the parenthesis to get the result:
public function getPost {
$user= User::find($id);
return $user->post;
}
When you use the parenthesis, you get the builder and not the result. example:
public function getPost {
$user= User::find($id);
return $user->post()->get();
}
OR
public function getPost {
$user= User::find($id);
return $user->post()->where('name', 'like', '%hello%')->get();
}
I think you need ->hasMany() relation if you want to check if user has any posts because the user can has many posts... and the code would be:
public function posts() {
return $this->hasMany('App\Post');
}
The call:
User::find($id)->posts;

Get user info from two tables using relationships in laravel

I have model user and user_data. I want to take some data from user and user data. My code looks like:
User model:
public function user_data()
{
return $this->hasMany('App\Models\UserData', 'user_id');
}
public function getUserById($id)
{
$user = User::findOrFail($id);
return $user;
}
UserData model:
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
User controller
public function getUser($id)
{
//$user = $this->model->getUserById($id);
$user = User::with('user_data')->find(3);
dd($user->sex);
return view('user', compact('user'));
}
How I can get data from two tables? When i dump sex i get null, but I have it in db.
you have to add also the local key in the relationship like this
public function user_data()
{
return $this->hasMany('App\Models\UserData', 'user_id','your local key');
}
$user = User::with('user_data')->where('id',$id)->first(); // Get the data like this
After that you can check what is it in like this
$user->user_data[0]->sex // Not $user->sex
If it's not working try to swap the foreign key and local key places.
Also you have to take the data like this

Sync element to a child on Laravel

My Shema database is
User Table
id
login
parent
Sign Table
id
name
user_id (Sign owner)
Pivot table user_sign
id
user_id
sign_id
My User model contain
public function signs() {
return $this->belongsToMany('App\Sign', 'user_sign');
}
public function parent(){
return $this->belongsTo('User', 'parent');
}
public function children(){
return $this->hasMany('User', 'parent', 'user_id');
}
And my Sign model contain
public function users() {
return $this->belongsToMany('App\User', 'user_sign')->select(['users.id','name']);
}
A parent user can attach / sync Sign to a child user via this route (he send sign_id and child_id)
Route::put('sign/share', 'SignController#share')
To do this action, in my controller i must check :
- if Owner of sign_id is $user_id
- If child_id is child of $user_id
And after that, i do my attach / sync.
Now, in my controller i have :
public function share(Request $request)
{
$userId = $request->input('user_id');
$sign = Sign::where('user_id', $userId)->find($id);
if(!$sign){
return response()->json(['message'=>'FAIL'], 404);
}
}
But I completely blocked after this... It's possible to check and attach in one line ?
Thanks for your help
As far as syncing/attaching you can use this sytanx
$user->roles()->sync([1, 2, 3]);
As given in Laravel Docs
You can do the both checks in the condition of IF and assign in case of true, thats how your controller will look like finally.
public function share(Request $request)
{
$userId = $request->input('user_id');
$signId = $request->input('sign_id');
$childId = $request->input('child_id');
if (Sign::find($singId)->user_id == $userId && User::find($userId)->child_id == $childId)
{
//Attach the sign to child user
User::find($childId)->signs()->attach($signId);
}
else
{
return response()->json(['message'=>'FAIL'], 404);
}
}

Categories