Laravel, changing form fields based on category selection - laravel

I have 2 categories in my db named 'House Rental' and 'Vehicle rental'
Users can post free ads based on the two categories.
My Listing model contains this:
Schema::create('listings', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('area_id');
$table->unsignedBigInteger('category_id');
$table->boolean('live')->default(false);
$table->softDeletes();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('area_id')->references('id')->on('areas')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
When a user visits add listing form, say he selects 'House Rentals' category, I want the add form to show fields like 'size', 'rooms', 'building_type', 'is_furnished', 'is_parking', etc.
At the same time if a user adds a listing and he selects 'Vehicle Rentals', I want the add form to show fields like 'vehicle_model', 'year_of_registration', 'condition', etc.
How would I go about doing this?

This is a single vue component that can be of assistance
<template>
<div>
<form #submit.prevent="iEdit ? iUpdate(): createMethod()">
<label> Select Rental </label>
<select class="form-control" #change="rentalChanged($event)" v-model="rentalForm.rental_category">
<option value="house rental"> House Rental </option>
<option value="vehicle rental"> Vehicle Rental </option>
</select>
<select v-if="house_rental">
<!-- show house rental options -->
</select>
<select v-if="vehicle_rental">
<!-- show vencle rental options -->
</select>
</form>
</div>
</template>
<script>
name: 'componentName',
data(){
return {
rentalForm: new Form({
rental_category: '',
another_form_field:'',
}),
iEdit : false,
vehicle_rental :false,
house_rental: false,
}
},
methods{
rentalChanged(event){
if(event.target.value == 'house rental'){
this.house_rental = true;
this.vehicle_rental = false;
}
if(event.target.value == 'vehicle rental'){
this.house_rental = false;
this.vehicle_rental = true;
}
},
iUpdate(){
//update method
},
createMethod(){
//create method
},
},
mounted(){
}
</script>
I hope it gives a clue I didn't test it.

Related

how to add more than one value using sync () method in laravel 5.8

what i am trying sync more than one value in the same table so far what i have done is that i have created model of the user and university and define the realtion between them as many to many to many such as the user has many unviersties and universities has many user
in my user model i have defined the realtion such as the
public function University()
{
return $this->belongsToMany(University::class);
}
in my university model
public function user()
{
return $this->belongsToMany(User::class);
}
i have also created a seprate migration since it is the many to many relationship
by the name of university_user
public function up()
{
Schema::create('university_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('university_id');
$table->timestamps();
});
}
in my controller i am trying to update the profile of user such as
public function ProfileUpdate(Request $request ,User $user)
{
$up=User::find($user->id);
$up->experince=$request->input('experince');
$up->city_id=$request->input('city');
$up->status=$request->input('account-type-radio');
$up->gender=$request->input('gender');
$up->year1=$request->input('year1');
$up->year2=$request->input('year2');
$up->University()->sync($request->Uni1);
$up->University()->sync($request->Uni2);
$up->location()->sync($request->location);
$up->subject()->sync($request->subject);
$up->grade()->sync($request->grade);
$up->update();
return redirect(route('user.index'));
}
in the form
<div class="row">
<div class="col-xl-4">
<div class="submit-field">
<h5>Institute</h5>
<select name="Uni1" id="Uni1">
#foreach($uni as $university)
<option value="{{$university->id}}">
{{$university->name}}
</option>
#endforeach
</select>
</div>
</div>
<div class="row">
<div class="col-xl-4">
<div class="submit-field">
<h5>Institute</h5>
<select name="Uni2" id="Uni2">
#foreach($uni as $uni1)
<option value="{{$uni1->id}}">
{{$uni1->name}}
</option>
#endforeach
</select>
</div>
</div>
The problem is only one value is getting stored in university_user table not two.. please tell me what my mistake is i'll be thank ful to u regards my laravel version is 5.8..

Relationships in laravel 5.4

when the admin select a category in <select></select> i want to get its id for insert it in a question table
table questions:
Schema::create('questions', function (Blueprint $table) {
$table->increments('id');
$table->string('question_text');
$table->string('type');
$table->integer('points');
$table->integer('temps_reponse');
$table->integer('categories_id')->unsigned();
$table->foreign('categories_id')->references('id')->on('categories');
$table->timestamps();
});
table categorie :
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('categorie');
$table->timestamps();
});
Question Model
class Question extends Model
{
public function categorie()
{
return $this->belongsTo(Categorie::class, 'categories_id');
}
}
Categorie Model
class Categorie extends Model
{
public function question()
{
return $this->hasMany(Question::class, 'question_id')->withTrashed();
}
}
I am blocked with it for a few hours please any help to solve it
my html
<label class="form-label">Choisir la categorie :</label>
<select class="" id="s2example-1" name="categorie">
<option></option>
#foreach ($categories as $categorie)
<option>{{ $categorie->categorie }}</option>
#endforeach
</select>
In order to send the id instead of the string back to the server, supply the value attribute on each option element: <option value={{$categorie->id}}>{{ $categorie->categorie }}</option>

Save one to many without creating

I just have a little problem. I have a one to many relationship. A team has many users. Many users have a team.
I have six teams of which the user has to choose one. How can I connect the team with the user without creating a new entry in the database 'team'?
User:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id')->unique();
$table->string('name');
$table->integer('team_id')->unsigned()->nullable();
$table->foreign('team_id')->references('id')->on('users')->onDelete('cascade');
$table->string('username')->nullable()->unique();
$table->string('email')->unique();
$table->string('phone')->nullable()->unique();
$table->string('avatar');
$table->string('slug');
$table->string('password');
$table->date('birthday');
$table->boolean('gender');
$table->rememberToken();
$table->timestamps();
});
}
Team:
public function up()
{
Schema::create('teams', function (Blueprint $table) {
$table->increments('id')->unique();
$table->string('name');
$table->string('image');
$table->string('image_thumbnail');
$table->timestamps();
});
}
Controller:
public function storeTeam($request)
{
$user = Auth::user();
$team = Team::findOrFail($request->team_id);
$user->team()->associate($team);
return redirect()->back()->with('success', lang::get('messages.team'));
}
View:
<div class="col-md-12">
<form method="POST" action="{{ URL::route('store.team') }}">
{{ csrf_field() }}
<ul class="row clients-dotted list-inline text-center">
#foreach ($teams as $team)
<li class="col-md-4 col-sm-3 col-6">
<div class="cc-selector">
<input id="team{{$team->id}}" type="radio" name="team" value="{{$team->id}}" />
<label style="background-image:url({{ $team->image_thumbnail }});" class="team-cc" for="team{{$team->id}}"></label>
<p>{{$team->name}}</p>
</div>
</li>
#endforeach
</ul>
<button type="submit" class="mb-50 float-right mr-20 btn btn-shadow-1 btn-primary">weiter</button>
</form>
route:
Route::post('/welcome/team', 'ProfilesController#storeTeam')->name('store.team');
i have a little problem with this and get the error:
Type error:
Type error: Too few arguments to function App\Http\Controllers\ProfilesController::storeTeam(), 0 passed and exactly 1 expected
Assuming that you're storing the team_id on the user model, you can use the associate method to set the primary key on the child -- user in this case
$user->team()->associate($team);
You would pass the selected team to the controller. Doesn't matter how. You can pass it as part of a route, or you can pass the team ID from a form and get it from the request.
You're expecting a variable to literally be passed to the controller called $request. What you want is to inject $request as a dependency. You can do that by typehinting the resolved variable like so:
public function storeTeam(Request $request)
Mind you, you'll need to have use Illuminate\Http\Request; at the top of your file, otherwise you will get errors regarding the Request class.

dynamic select options depend on another select option in laravel

I have two tables as users and departements. My departments table have two columns as id and title and my users table contains users information columns and one exta column as dept_id which is related to department table id.
I want to create a dropdown select option for departement and when a departement is selected the users which have that related department id should be displayed into another dropdown, how can i do that..?
i am fetching all users and departments data in controller and sending it to view.
my controller is....
public function index()
{
$user = DB::table('users')->get();
$dept = DB::table('departments')->get();
return view('userview', compact('user', 'dept'));
}
and my view is....
<select class="form-control" id="department" name="department" >
#foreach($dept as $dept)
<option value="{{ $dept->id }}">{{ $dept->name }}</option>
#endforeach
</select>
<select class="form-control" id="user" name="user" >
<option> </option>
</select>
I would use an Ajax request to fetch the related users and populate the 2nd list. Set up the relation in the User and Department models like:
// Department.php
public function users() {
return $this->hasMany(User::class);
}
// User.php
public function department() {
return $this->belongsTo(Department::class);
}
In your controller:
// DepartmentController.php
public function index() {
return view('userview', [
'departments' => Department::all()
]);
}
public function users(Request $request, $id) {
if ($request->ajax()) {
return response()->json([
'users' => User::where('dept_id', $id)->get()
]);
}
}
Then in your view, setup an event listener for the change event on the first select:
<select class="form-control" id="department" name="department" >
#foreach($departments as $dept)
<option value="{{ $dept->id }}">{{ $dept->name }}</option>
#endforeach
</select>
<select class="form-control" id="user" name="user" ></select>
<script>
$('#department').on('change', e => {
$('#user').empty()
$.ajax({
url: `/departments/${e.value}/users`,
success: data => {
data.users.forEach(user =>
$('#user').append(`<option value="${user.id}">${user.name}</option>`)
)
}
})
})
</script>

Reorder menu items without affecting database id

I have a menu in my Laravel application which lists tags. I want to be able to add more tags and change their order, but I don't want to affect the underlying database ids for each tag. Because that would break any data I have already associated with them. So I thought I add an extra column to my database called 'display_order' like so:
Database:
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->integer('display_order');
$table->string('name');
$table->timestamps();
});
Now I want to create a view to let the user change the value of the display_order field. Initially I show a page which prints each tag and its display_order and allows the user to update the value in a text field:
Controller:
public function showTagsOrder()
{
$tags = Tag::all()->sortBy('display_order');
return view('menu.tags', compact('tags'));
}
Route:
Route::get('/menu/tags', ['as' => 'menu_tags', 'uses' => 'MenuOrderController#showTagsOrder']);
View:
{!! Form::open(['action' => 'MenuOrderController#updateTagsOrder']) !!}
#foreach($tags->chunk(18) as $chunk)
<div class="col">
#foreach($chunk as $tag)
<p><label>{!! $tag->name !!}</label><input type="text" name="tag_array[{!! $tag->id !!}]" value="{!! $tag->display_order !!}" class="numeric" />
#endforeach
</div>
#endforeach
<p>{!! Form::submit('Submit') !!}
{!! Form::close() !!}
When the form is submitted I then have the following function in my controller:
public function updateTagsOrder(TagsMenuRequest $request)
{
$i = 1;
foreach($request->tag_array as $tag_value)
{
$tag = new Tag;
$tag = Tag::find($i);
$tag->display_order = $tag_value;
$tag->save();
$i++;
}
flash()->overlay('The order of tags in the menu has been udpated!', 'Congratulations');
return redirect('/');
}
But this doesn't work. How would I rewrite this so I assigned the correct value for display_order to each tag. I'd be very grateful for your help.
foreach($request->tag_array as $tag_id => $tag_value)
{
$tag = Tag::find($tag_id);
$tag->display_order = $tag_value;
$tag->save();
}

Resources