I have been struggling with this for a while, am a new developer with very little experience. So am working on a project dealing with drugs and diseases. There exists a many to many relationship.
Drug model
public $timestamps=false;
public function disease()
{
return $this->belongsTo('App\Disease');
}
Disease model
public $timestamps=false;
public function drug()
{
return $this->belongsTo('App\Drug');
}
I want to create relationships in the Disease_Drug pivot table using forms.
form.blade.php
<label>Disease</label>
<select class="form-inline input-sm " name="disease" id="disease">
#foreach($diseases as $key => $disease)
<option value="{{$disease->id}}"> {{$disease->name}}</option>
#endforeach
</select>
<label>Drugs</label><br>
#foreach($drugs as $key=>$drug)
<input type="hidden" name="drug[]" value="0" />
<input class="checkbox-inline" type="checkbox" name="drug[]"value="{{ $drug->id }}" id="{{ $drug->id }}">{{ $drug->name }} <br>
#endforeach
<button type="submit" class="btn btn-primary">Submit</button>
I have a disease_drug controller
public function form()
{
$diseases = Disease::all();
$drugs = Drug::all();
return view('admin.form')
->with('diseases', $diseases)
->with('drugs', $drugs);
}
public function store(Request $request)
{
$diseases = $request->get('diseases.ids');
$drugs = $request->get('drugs.id', []); // Empty array by default if no checkbox checked.
$diseases->drugs()->sync($request->input('drugs', []));
}
I am unable to save the results in the database. I am really clueless on this so kindly help me out.
If relation between drugs and disease is Many To Many then your relation function should be as:
Drug model
public function disease()
{
return $this->belongsToMany('App\Disease');
}
Disease model
public function drug()
{
return $this->belongsToMany('App\Drug');
}
You are using belongsTo() function instead.
Related
I am trying to fetch a list from the database into a <select> for the form.
I have a controller with classes (index, getLocations, create, store, edit, update, destroy)
public function getLocations($locationList)
{
$locationList = Locations::select('id', 'locationName')->get();
return view('pages.dataEntry.reports.reports', compact('locationList'));
}
getLocation has its own Model:
class Locations extends Model
{
use HasFactory;
protected $table = 'kaec_locations';
}
and I get undefined variable $locationList is undefined
<select class="form-select" name="caseLocation">
<option value="none" selected disabled>Select Location</option>
#foreach ($locationList as $item)
<option value="{{ $item->id }}"> {{ $item->locationName }} </option>
#endforeach
</select>
Is this a good practice? to have a separate Model for locations?
How come the variable is undefined? Should it be included in the route?
Route::controller(ReportController::class)->group(function () {
Route::get('reports', 'getLocations');
Route::get('reports', 'index')->name('reports.index'); // Index page (DataTable)
Route::get('reports/create', 'create')->name('reports.create'); // The form for adding new records
Route::post('reports/create', 'store')->name('reports.store'); // Add new to DB
Route::get('reports/edit/{report}', 'edit')->name('reports.edit'); // The form for editing records
Route::put('reports/edit/{report}', 'update')->name('reports.update'); // Update record to DB
Route::get('reports/{report}', 'destroy')->name('reports.destroy'); // Delete from DB
});
Got it. I do not need to make a function for this. I already have function for adding new data create(). The Create refers to the blade file of the form I want to display that <select>
So I just removed the getLocations() and added the code to create()
/**
** Add new Record Page.
**/
public function create()
{
$locationList = Locations::all();
return view('pages.dataEntry.reports._addForm', compact('locationList'));
}
Tables: Item has boolean "onloan"
Patron(id, name), Item(id, name, onloan), Transactions (patron_id, item_id, loaned, due, returned)
Relationships:
Patron.php
public function transaction ()
{
return $this->hasMany(Transaction::class);
}
Item.php
public function transaction ()
{
return $this->hasMany(Transaction::class);
}
Transaction.php
public function item()
{
return $this->belongsTo(Item::class);
// return $this->belongsTo('App\Item','item_id');
}
public function patron()
{
return $this->belongsTo(Patron::class);
}
View: create.blade.php
<label for="item_id">Item</label>
<select name="item_id" id="item_id" class="form-control select2">
#foreach($items as $item)
<option value="{{ $item->id }}">
{{ $item->barcode }} - {{ $item->name }}
</option>
#endforeach
</select>
TransactionController.php
This part is where I have problem, Two (2) tables need to be updated.
i.e.
Transactions table: (this part is already working, it's ok)
Name......| Item..........| Loaned.....| Due..
John Doe | Harry Potter | 09/22/20 | 09/23/20
Items table: (this part I don't know how to add it in the Controller)
Name...........| Onloan
Harry Potter | 1
• how update a foreign table (Items) in this controller so that
the "onloan" value of that $item->id is 1.
public function store(TransactionRequest $request)
{
Transaction::create([
'patron_id' => $request->patron_id,
'item_id' => $request->item_id,
'loaned' => $request->loaned,
'due' => $request->due,
]);
//This is what I tried, but it's not working.
Item::find($request->item_id);
$item->update([
'onloan' => 1,
]);
Please help. Thank you.
Υou can write it that way
Item::find($request->item_id)->update(['onloan' => 1,]);
Create you can also do it
Transaction::create([$request->all()]);
I have three models :
Serie ($id)
public function saisons()
{
return $this->hasMany(Season::class);
}
public function episodes()
{
return $this->hasManyThrough(Episode::class, Season::class);
}
Season ($serie_id)
public function serie()
{
return $this->belongsTo(Serie::class);
}
public function episodes()
{
return $this->hasMany(Episode::class);
}
Episode ($season_id)
public function season()
{
return $this->belongsTo(Season::class);
}
public function serie()
{
return $this->BelongsToThrough(Serie::class, Season::class);
}
I would like to show one specific season from a serie with the episodes associated
My view
<h1 class="title">{{$serie->seasons->number}}</h1>
#foreach ($serie->seasons->episodes as $episode)
<div class="row">
<div class="columns">
<div class="col">
{{$episode->number}}
{{$episode->name}}
#if(isset($episode->programmation->date))
{{$episode->programmation->date}}
#endif
#if (($episode->season_finale) == '0')
Non
#elseif (($episode->season_finale) == '1')
Oui
#endif
#foreach ($episode->chaines as $chaine)
{{$chaine->name}}
#endforeach
</div>
</div>
</div>
#endforeach
Route
Route::get('/serie/{serie}/saison/{season}', 'Front\SaisonController#show')->name('saison.show');
For my url, I choose to show the number of the saison and not the id and I think that's the problem.
How can I do that in a proper way ?
I think this approach can help you.
$serie = Serie::where('id',$id)->with('seasons'=>function($query) use ($season_id) {
$query->where('season_id',$season_id)->with('episodes')->get();
})->get();
Ok, someone help me to find the right answer :
$serie = Serie::findOrFail($serie);
$season = Season::where('serie_id', $serie->id)->where('season.number', $season)->first();
i am trying to make a list of locations that you can rent. but to rent the place you need to fill in some information. to fill in this information you excess another page. how do i make it so laravel knows the page belongs to a certain location
this is what ive done now but i keep getting the error:
Call to undefined method App\Reservation::location()
as soon as i have filled in the fields of information
this is the blade file that links to the the create reservation file
#foreach
($locations as $location => $data)
<tr>
<th>{{$data->id}}</th>
<th>{{$data->name}}</th>
<th>{{$data->type}}</th>
<th><a class="btn" href="{{route('Reservation.index', $data->id)}}">rent</a></th>
</tr>
#endforeach
this is the create reservations blade
<form action="{{ route('location.store') }}" method="post">
#csrf
<label>title</label>
<input type="text" class="form-control" name="name"/>
<label>type</label>
<select>
<option value="0">klein</option>
<option value="1">groot</option>
</select>
<button type="submit" class="btn">inschrijven</button>
</form>
this is what the location controller looks like
public function store(Request $request)
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($request->location());
$location->save();
return redirect('/location');
}
and the relationships in my models should also work
class Reservation extends Model
{
public function locations()
{
return $this->belongsTo('Location::class');
}
}
class Location extends Model
{
public function reservations()
{
return $this->hasMany('Registration::class');
}
}
ive been stuck at this all day and i really dont know where to look anymore
The error you are getting is because of the wrong function name, you are calling location, while it is locations.
public function locations(){}
&
$location->location()->associate($request->location());
and you can pass the variable as a query parameter, you'll need to pass this data as an array in your blade file.
Web.php
Route::get('/somewhere/{id?}, function(){
//do something
})->name('test');
Blade
route('test', ['id' => $id]);
Controller Method
public function store(Request $request, $id) //Adding the query parameter for id passed in Route.
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($id);
$location->save();
return redirect('/location');
}
Ok.
I'm building a property app. I have a friends system implemented in the app. I'm using this to allow a landlord to add a tenant and this works as a connection. My question is how would I associated one of the landlords properties with the request when it is send.
At the moment, when a request is sent, the following is posted to the database. User_id (Landlord), Tenancy_id (Tenant), Accepted (false). I would like to post a property address with this also, but I'm stuck on how to do that.
I have a form, where I have the landlords name, and tenants name, but also a list of the landlords property. I have no idea how to send this to the database. As it's not a normal store method. I will post the code.
The add method in the ACCOUNT CONTROLLER
public function getAdd($id){
$user = User::where('id', $id)->first();
//If the user can be found
if(!$user){
return redirect('/')->with(['status', 'Profile Not Found']);
}
if(Auth::user()->id === $user->id){
return redirect()->route('home');
}
//If current sign in user has request pending with the users
//If the uer has a request pending with auth user
if (Auth::user()->hasTenancyRequestsPending($user) ||
$user->hasTenancyRequestsPending(Auth::user())){
return redirect('/account/{{$user->id}}')->with('status', "Friend request already pending");
}
//Check if tenancy already exists
if(Auth::user()->isInTenancyWith($user)){
return redirect('/account/{{$user->id}}')->with('status', "Already i a tenancy");
}
//After passing all checks. Add other account
//Landord is adding the tenant
Auth::user()->addTenancy($user);
return redirect('/account/{{$user->id}}')->with('status', "Request Sent");
}
The create FORM
The properties variable is loaded from a controller which holds all properties owned by a landlord.
<form action="/account/{{$user->id}}/add" method="POST">
{{ csrf_field() }}
<select class="form-control" id="property_address" name="property_address">
<!--Gets all counties from DB -->
#foreach ($properties as $property)
<option value={{$property->id}}>{{$property->address . ', ' . $property->town . ', ' . $property->county}}</option>
#endforeach
</select>
<label for="landlord-name">Landlord Name</label>
<select class="form-control" name="landlord-name">
<option value="{{Auth::user()->name}}">{{Auth::user()->name}}</option>
</select>
<label for="tenand-name">Tenant Name</label>
<select class="form-control" name="tenant-name">
<option value="{{$user->name}}">{{$user->name}}</option>
</select>
<button class="mt-2 btn btn-primary" type="submit">Create Tenancy</button>
</form> <!-- ./form -->
THE User model which has the methods to add friends
//Tenancies of this uers. User model, tenancy table.
public function tenanciesOfMine(){
return $this->belongsToMany('App\User', 'tenancies', 'user_id', 'tenancy_id');
}
//Users who have this user as a friend
//Inverse of user tenncies -> Both users have tenancy if one exists. One user can't be in a tenancy with someone who is not in tenacy with them.
//Like friends on FB. You can't be friends with someone, without them being friends with you also.
public function tenancyOf(){
return $this->belongsToMany('App\User', 'tenancies', 'tenancy_id', 'user_id');
}
//If a tenancy is accepted, create the tenancy ie friendship.
public function tenancies(){
//Getting friends of this user. Where accepted is true
return $this->tenanciesOfMine()->wherePivot('accepted', true)->get()->
//merge the inverse. Tennancy created with both users
merge($this->tenancyOf()->wherePivot('accepted', true)->get());
}
//Request hasn't yet been accepted. Display list of pending requests
public function tenacyRequests(){
return $this->tenanciesOfMine()->wherePivot('accepted', false)->get();
}
//Inverse of Tenancy Requests
public function tenancyRequestsPending(){
return $this->tenancyOf()->where('accepted', false)->get();
}
//If a user has a request pending from another user
public function hasTenancyRequestsPending(User $user){
return (bool) $this->tenancyRequestsPending()->where('id', $user->id)->count();
}
public function hasTenancyRequestsReceived(User $user){
return (bool) $this->tenacyRequests()->where('id', $user->id)->count();
}
//Add tenancy
public function addTenancy(User $user){
$this->tenancyOf()->attach($user->id);
}
//Add tenancy
public function acceptTenancyRequest(User $user){
$this->tenacyRequests()->where('id', $user->id)->first()->pivot->update([
'accepted' => true,
]);
}
Here are the migrations for Tenancies (Which holds the landlord and Tenant) relationship.
Schema::create('tenancies', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('tenancy_id');
$table->string('property_address');
$table->boolean('accepted')->default('0');
});
And for property
Schema::create('property_adverts', function (Blueprint $table) {
$table->increments('id');
$table->string("photo");
$table->string('address');
});