I would like to ask for help, please advise how to solve such problems in laravel
how to make an application like a vehicle ticket application, to limit if there are 5 people on car A, then user can not choose car A in listbox (item listbox carA disable) when booking.
I am confused where to start
I am currently thinking of creating 3 tables
users (id, name,car_id, created_at, updated_at)
cars (id, car_name, created_at, update_at)
I am confused what should be done to the controller Thank you very much
thanks to all of you, i can start the first step.
currently
on the controller
public function create(){
$list=MCars::all();
return view('booking/create')->with('sent_list',$list);
}
on the view
<select name="car" value="{{ old('car')}}">
#foreach($sent_list as $a)
<option value="{{$a->id}}">{{$a->car_name}}</option>
#endforeach
</select>
I want only cars that contain users <5 that appear on the view
maybe i should put this somewhere
SELECT DISTINCT cars.id, cars.car_name, COUNT(users.car_id) from cars INNER JOIN users ON cars.id = users.car_id
The relationship can be like this:
a user belogsTo a car and the car hasMany users
So the Car model class should be:
..
class Car extends Model
{
public function users()
{
return $this->hasMany('App\User');
}
}
And the User model:
class User extends Model
{
public function car()
{
return $this->belongsTo('App\Car');
}
}
Eloquent will automatically determine the proper foreign key. So, here Eloquent will assume the foreign key on the User model is car_id.
Access the collection of users by accessing the users property.
$users = App\Car::find(1)->users;
foreach ($users as $user) {
//
}
In the UserController use:
$user = App\User::find(1);
echo $user->car->name;
This is how the Eloquent works!
Now use the custom logic for limit(5).
To retrieve the number of cars as users:
public function getTotalUsersAttribute()
{
return $this->hasMany('Car')->whereUserId($this->user_id)->count();
}
And:
if(getTotalUsersAttribute() >= 5) {
// dismiss this function with an err msg
}
// otherwise add user to car
Find similar cases and solution from the official docs.
you can make the registration for user, user will insert their name(according to your table), but i'll suggest for inserting new column email and password for login system. if they not login, they cant booked cars. they must register and login to booking cars.
after user login, the car can be booked, you must create form for it. the code something like this
$cars_id = request::get('id');
$total_passenger = DB::table('passenger')->WHERE('car_id',$cars_id);
if(count($data) < 5){
//do insert data into passenger
}else{
//windows alert / whatever
}
Related
Hello as the title says I'm not sure why my code is not showing the "First Name" for a user but it shows the ID only I have tried to do a lot of different methods to solve this but I'm rather a beginner in laravel so I thought It would be best if I asked for help by now
To explain a little the field "recieverID" is a foreign key of the table Users that shows the ID of the users
So here is the model named "Remark"
class Remark extends Model
{
protected $guarded =[];
public function user(){
return $this->belongsTo(User::class);
}
}
This is the Remark Controller
public function index()
{
if(Auth::guard('admin')->check())
{
$users = User::all();
$remarks = Remark::latest()->get();
return view('admin.remark.index', compact('users'),compact('remarks'));
}
It has more code under it but I only need it for this part, I added the $users and compact users because I tried to add 2 foreach loops on the view to see how it looks but it didn't quite work as i thought it might
This is the view I want to show the Name instead of the ID
#foreach($remarks as $remark)
<tr>
<td>{{$remark->recieverID->user->first_name}}</td>
<td>{{$remark->title}}</td>
<td>{{$remark->subject}}</td>
<td>{{$remark->message}}</td>
<td>{{$remark->sender}}</td>
</tr>
#endforeach
Thank you for your time
First of all, you need to change your relationship as below. If you don't pass foreign key then it assumes that you have foreign key as(user_id) in the table. but you have recieverID in the table. So, you need to define it.
public function user(){
return $this->belongsTo(User::class,'recieverID','id');
}
Now you can add it blade file.
<td>{{$remark->user->first_name}}</td>
I have the following:
//users table
id
name
email
remeber_token
role_id
//roles table
id
name
//products table
id
name
//product_prices
role_id
product_id
price
The price of the product will vary depending on the user role, how to define the correct relationship so in blade I can do something like:
$product->price
and that will return the correct price depending on the user and the product?
I believe that when you say the user role, you refer to the role of the authenticated user.
The easiest approach is to define a HasOne relationship on the product model:
class Product
{
public function price()
{
return $this->hasOne(Price::class)->where('role_id', auth()->user()->role_id)
}
}
So from the view, you can simply say:
// Lets use optional() because there may not be any price for that product and user.
optional($product->price)->price
If there are many products involved, then using sub queries would make more sense.
class ProductsController extends Controller
{
public function index()
{
$products = Product::addSelect(['right_price' => Price::select('price')
->whereColumn('product_id', 'products.id')
->where('role_id', auth()->user()->role_id)
->limit(1)
])->get()
return view('products.index', compact('products'));
}
}
And then in the view:
#foreach($products as $product)
<p>{{$product->right_price}}</p>
#endforeach
For more info, pls check out this article.
I'm trying to get all the properties, in a watchlist(s) where the list has a user id.
The relationship is set up as follows.
Each watchlist is related to a user id. Each Property has a watchlist id.
I need all properties, in all the watchlists belonging to that user.
The watchlist gets the user_id automatically upon creation.
Here are my models
Watchlist
public function properties(){
return $this->hasMany('App\WatchedProperties');
}
public function user(){
return $this->belongsTo('App\User');
}
WatchedProperties
public function watchlist(){
return $this->belongsTo('App\Watchlist');
}
Query
Gets all books in every list disregarding user ids and list ids
$Watchlists = WatchedBooks::all();
Currently gets all books regardless of userid.
I need all books in all of the user's lists.
A user could have multiple lists
List A
List B
So something like
All books from all lists where the list id is related to user id.
This is what the Watchlist DB looks like
WatchlistDB
This is what the WatchedBooks DB looks like
Books in watchlist
Laravel has a beautiful solution for this: you can add a ->hasManyThrough relation to the user model. You can find more information about this type of relation in the Laravel documentation about Eloquent relationships.
The user model will look like this:
class User extends Model {
[...]
public function watchedBooks()
return $this->hasManyThrough('App\WatchedBook', 'App\Watchlist');
}
[...]
}
Then you can get all the WatchedBooks, associated with the user, using
$user->watchedBooks;
or
$user->watchedBooks()->yourBuilderQueryHere()->get();
whereHas allows you to query in relationships. More information on this can be found at https://laravel.com/docs/5.6/eloquent-relationships#querying-relationship-existence
$Watchlists = WatchedBooks::whereHas('watchlist', function($query) use ($user_id){
$query->where('user_id', $user_id)
})->get();
The script above gets all WatchedBooks that are associated with a Watchlist that is owned by a user ($user_id).
I am trying to get a feel around the laravel ORM and I have the following models.
I have a:
user table with- id, firstname, lastname
city table with - id, name
usercity table with - user_id, city_id
The usercity table tracks the cities the user has visited.
I added the following in city model:
public function usercity()
{
return $this->hasMany('App\UserCity');
}
And another function in user model
public function usercity()
{
return $this->hasMany('App\UserCity');
}
I also added a model for UserCity and added following function there.
public function city()
{
return $this->belongsTo('App\City');
}
public function user()
{
return $this->belongsTo('App\User');
}
Now, the goal is to retrieve all the cities a user has visited. I used the following function.
$usercities = User::where('id','=',1)->first()->usercity()->get();
This works in the sense that it retrieves the user_id and city_id.
What would i need to do to get all the fields in the city table also?
Current response:
[[{"user_id":"1","city_id":"1"},{"user_id":"1","city_id":"2"},{"user_id":"1","city_id":"3"},{"user_id":"1","city_id":"4"}]]
I might be able to use inner join but I wanted to see if there was another way to retrieve the data which safely populates the data for me.
What you really have is a many-to-many relationship between users and cities, with the usercity table being the pivot table. Laravel uses the BelongsToMany relationship to implement this. You'll need to make a few changes to get this to work.
In your city model:
public function users() {
return $this->belongsToMany('App\User', 'usercity');
}
In your user model:
public function cities() {
return $this->belongsToMany('App\City', 'usercity');
}
You can get rid of the UserCity model. There is usually no reason to need a model for the pivot table.
The usercity table may need to be updated to add an id field as the primary key. I've not tried it without one, however, so it may work as you have it. Also, if you wanted, you could rename the table to city_user to conform to Laravel conventions, and then you wouldn't need to specify the table name in the relationship definitions.
Once your relationships are setup correctly, you can access a user's cities via the cities relationship on the user, and you can access a city's users via the users relationship on the city. For example:
// all of the cities visited by user 1
$user = User::find(1);
$usercities = $user->cities;
// all of the users that have visited city 1
$city = City::find(1);
$cityusers = $city->users;
You can find more information about the relationships in the documentation here.
I'm wondering how, but it's bit confusing.
I have fine belongs to many relation between users and groups tables as well as appropriate models for all of that.
But i also have table students, where not all users are student so i students table i maintain user_id field.
My question would be: Can i use pivot table "group_user" for relations between student and group model, in students table i have "user_id" field? and how?
I tried something like
public function students()
{
return $this->belongsToMany('Student','group_user','group_id','user_id');
{
but i don't see the way how to tell eloquent not to take students.id but to take students.user_id???
Assuming these relations:
Subject belongsTo Group
Group belongsToMany User
User hasOne Student
you can easily do this:
$subject = Subject::find($someId);
// of course for multiple subject use eager loading:
// $subjects = Subject::with('group.users.student')->get();
$users = $subject->group->users; // related users
foreach ($users as $user)
{
$user->student; // null|student model
}