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
Related
I have 4 table : Users, CompanyRegister, VoucherDetails, Addvoucher.
So the Authenticate Users Id will be submit as user_id in companyRegister table,and then companyRegister ID will be submit as company_id in Voucherdetails table, and lastly voucherDetails Id will be submit in addVoucher table as voucher_ID. I am new to using eloquent and also laravel, I cant understand why I cant get the id from voucherdetails and submit in addvoucher but I can get id from companyregister and submit in company_id in voucherdetails. I'm using the same method to get id but not work, I hope can get solution and explanation here,Thank you in advance!!
My users model
public function companyregisters()
{
return $this->hasOne('App\companyregisters');
}
public function voucherdetails()
{
return $this->hasMany('App\voucherdetails');
}
public function addvoucher()
{
return $this->hasMany('App\addvoucher');
}
public function roles()
{
return $this->belongsToMany('App\role');
}
public function hasAnyRoles($roles)
{
if($this->roles()->whereIn('name', $roles)->first()){
return true;
}
return false;
}
public function hasRole($role)
{
if($this->roles()->where('name', $role)->first()){
return true;
}
return false;
}
my companyregister model
public function User(){
return $this->belongsTo('App\User');
}
public function voucherdetails()
{
return $this->hasMany('App\voucherdetails');
}
my voucherdetails model
public function User(){
return $this->belongsTo('User');
}
public function companyregisters(){
return $this->belongsTo('App\companyregisters');
}
public function addvoucher()
{
return $this->hasOne('App\addvoucher');
}
my addvoucher model
public function User(){
return $this->belongsTo('App\User');
}
public function voucherdetails(){
return $this->belongsTo('App\voucherdetails');
}
my voucherdetailsController
public function store(Request $request){
$voucherdetail = new voucherdetails();
$voucherdetail->title = $request->input('title');
$voucherdetail->description = $request->input('description');
$voucherdetail->user_id = Auth::user()->id;
$id = Auth::user()->id;
$user = User::find($id);
$company = $user->companyregisters;
$companyId = $company->id;
$voucherdetail->company_id = $companyId;
$voucherdetail->save();
return redirect()->to('addvoucher');
}
my addvoucherController
public function store(Request $request){
$addvoucher = new addvoucher();
$addvoucher->voucherTitle = $request->input('voucherTitle');
$addvoucher->voucherCode = $request->input('voucherCode');
$addvoucher->user_id = Auth::user()->id;
//Here(the voucherdetails id cant get to submit in voucher_id)
$id = Auth::user()->id;
$user = User::find($id);
$voucher = $user->voucherdetails;
$voucherID = $voucher->id;
$addvoucher->voucher_id = $voucherID;
$addvoucher->save();
return redirect()->to('displayVouchers');
}
This code works because companyregisters is a hasOne relationship for which the docs say:
Once the relationship is defined, we may retrieve the related record
using Eloquent's dynamic properties.
public function companyregisters()
{
return $this->hasOne('App\companyregisters');
}
$company = $user->companyregisters; // ie this returns the single related record
$companyId = $company->id; // and it has an `id` property, all good here
However, this code fails because voucherdetails is a hasMany relationship for which the docs say:
Once the relationship has been defined, we can access the "collection"
of comments by accessing the comments property.
More info on collections
public function voucherdetails()
{
return $this->hasMany('App\voucherdetails');
}
$voucher = $user->voucherdetails; // ie this returns a "collection" of related records
$voucherID = $voucher->id; // this "collection" does NOT have an id property, but each record IN the collection does.
In summary, either your relationship is defined incorrectly (hasMany vs hasOne) or, you'll need to loop over the related records to get the id from each.
How do you display all list of admin that have column with the is_admin=1? with this query? because we are not passing any data in showListAdmin.
public function Admin()
{
$users = User::all();
return view('admin.admins')->with('users',$users);
}
simply use where ....
public function showListAdmin()
{
$users = User::where('is_admin',true)->get()->all();
return view('admin.admins')->with('users',$users);
}
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;
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
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();