How to Store Data from select html tag to DB and display it...Laravel - laravel

Laravel
I have 3 tables
1- users => id + name + email + password
2- categories => id + name
3- category_user => user_id + category_id
I want the users to choose their favorite categories so that only the articles for that category appear.
here the page to select category:
<div class="form-group">
<label for="body">Category</label>
<select name="categories[]" id="" multiple>
#foreach ($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
#endforeach
</select>
how can I store this data in the category_user table? (with validate)
Also, how can I display only articles belonging to the selected categories?

If you dump and die your request data in controller, you will see categories as an array. you can iterate through categories by a foreach loop and save it to category_user table. Don't forget to use current user id as user_id.
foreach ( $request->categories as $categoryId ) {
CategoryUser::create( [ 'user_id' => auth()->user()->id, 'category_id' => $categoryId ] )
}
For display need some more information about articles table. Is one article belongs to one or many category?

Related

Laravel/Livewire differentiate two dropdown menus in of the same model

Context: I have a category with subcategories; these categories load using a foreach in my Blade file. These subcategories have a dropdown to select data from them. My problem is that when I change the dropdown of one of the subcategories, the other subcategories change too.
#foreach ($subcategories as subcategory )
<x-simple-select wire:model="subcategory_id" :wire:key="$subcategory->id"
name="subcategory" id="{{$subcategory->id}}"
:options='$types' value-field='subcategory' text-field='subcategory'
/>
#endforeach
I want to save the selected data from the dropdown using updatedSubcategoryId($value), but I don't know how to save it since all the subcategories are changed and not just one.
ok I figured out to do.the all idea was wrong (i'm new in livewire).
In case it serves to someone:
<form wire:submit.prevent="save()">
#foreach ($subcategories as $key => $subcategory )
<x-simple-select wire:model.defer="subcategories.{{$key}}.id" :options='$types' />
#endforeach
<button type="submit">save</button>
</form>
and then in the controller:
protected $rules = [
'subcategories.*.id' => '',
];
public function save()
{
$this->validate();
foreach ($this->subcategories as $subcategory) {
$subcategory->save();
}

insert into 2 tables (pivot) array values from multiple select dropdown list

I work with events and years, one event can be in several years and a year can have
several events (pivot table created between the two tables).
I change my single dropdown list in multiple list :
<select id="year_id" type="text" class="form-control selectpicker #error('year_id') is-invalid #enderror" name="year_id[]" required multiple>
<option disabled>--Choisir--</option>
#foreach($years as $year)
#if(old('year') == $year->id)
<option value="{{ $year->id }}" selected>{{ $year->name }}</option>
#else
<option value="{{ $year->id }}">{{ $year->name }}</option>
#endif
#endforeach
</select>
The goal is to select several years for one same event.
I don't know why, but I think I'm not able to validate the form.
This is my controller code :
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'mnemonique' => 'required|string|max:255',
'color' => 'required|string|max:255',
'year_id[]' => 'required|array',
'year_id[].*' => 'required|integer|exists:years,id'
]);
$evenement = new Evenement();
//dd($validatedData);
// $evenement->create($validatedData);
$evenement = Evenement::create($validatedData);
$evenement->years()->sync([$validatedData['year_id[]']]);
I'm not able to insert the events into the pivot table and the new event into the event table.
If I use dd(), I still have a refresh of the form, I think I don't go into the controller...
Do you see something please ?
Thank you in advance.
Change validation rule to
'year_id' => 'required|array',
'year_id.*' => 'required|integer|exists:years,id'
To show Error message in view
#error('year_id')<div class="invalid-feedback">{{$message}}</div> #enderror
and
#if($errors->has('year_id.*')) <div class="invalid-feedback">Selected Year doesnt exists</div> #endif
While saving into database
$evenement->years()->sync($validatedData['year_id']);

Laravel checkbox problem which I cannot update the pivot table

I'm working on a laravel application. In laravel I'm trying to update a row from a pivot table. In this application I have three tables:
issues: id, title, description
categories: id, name
category_issues:(pivot table) id, issue_id, category_id
In laravel I'm trying to update a row from a pivot table. I have this relationships:
Issue.php
public function categories() {
return $this->belongsToMany('App\Category', 'category_issues');
}
Category.php
public function issues() {
return $this->belongsToMany('App\Issue', 'category_issues');
}
A issue can have many categories.
Html code for displaying category section:
<div class="form-group row">
<label for="category" class="col-md-4 col-form-label text-md-right">{{ __('Category :') }}</label>
<div class="form-check col-md-6">
#foreach ($categories as $category)
<input type="checkbox" name="category[]" id="{{ $category->id }}" value="{{ $category->id }}"
{{ in_array($category->id, $issue->categories->pluck('id')->toArray()) ? 'checked' : '' }}>
<label for="{{ $category->id }}"> {{ $category->name }} </label>
#endforeach
</div>
</div>
Here is the update function file:
public function update(Issue $issue)
{
request()->validate([
'title'=> ['required', 'min:3'],
'description'=> ['required', 'min:3'],
'category' => ['required']
]);
$issue->title = request('title');
$issue->description = request('description');
$issue->save();
//Category_Issue Update
$categoryIssue = new CategoryIssue;
$cats = request('category');
foreach ($cats as $cat) {
$categoryIssue->updateOrCreate([
'issue_id'=> $issue->id,
'category_id' => $cat
]);
}
return redirect('issues')->with('success', 'Issue has been updated');
}
Instead of doing the creation / update on the CategoryIssue model (do you even have a CategoryIssue model?), Laravel makes this really easy to update the pivots of a relationship all at once, with the sync() method. You've set up the relationships correctly already per your code above.
In your update() method, you already have your Issue model, and have saved it. You have a set of categories coming in from the form via the $request object (or none if user didn't choose any), so you can then update the pivot like this:
$issue->categories()->sync($request->get('category', []));
Leaving a blank array as the second argument is optional. One small suggestion: maybe make the name of the field on the form 'categories' instead of 'category' just to keep it easy to remember it is an array coming in.

Get data Based On Selected Value in Drop Down menu - Laravel 5.4

I have two tables posts and category.
My controller:
public function index()
{
$posts = Post::orderBy('id', 'desc')->get(['category']);
$data = DB::table('posts')->paginate(5);
$category = DB::table('category')->pluck('cname','id');
return view('posts.index', [
'posts' => $posts,
'category'=> $category,
'posts' => $data
]);
}
My blade:
<select class="form-control" name="category" id="category_add">
<option value="">Select Category</option>
#foreach($category as $key=>$value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
Now my code shows a drop down data from the database...
What I need is: When I select the drop down category it should only shows the particular category of data in the view dynamically
Any one help
Did you mean after selecting a category from the dropdown there will be another section which will show data about that specific category?
One way to do it is through ajax request. I dont know if i got your question right or wrong. can u explain a bit if i got it wrong?

Laravel RESTful edit screen with multiple tables

I have 3 tables for storing business details. The main table and a phone numbers table, as a business can have any number of phone numbers attached to it.
Table 1 - Business listing
Table 2 - Business phone numbers
Table 3 - Links table 1 to table 2 as shown here
1 id int(11) No None AUTO_INCREMENT
2 listings_id int(11) No None
3 listingsphone_id int(11) No None
4 created_at timestamp
5 updated_at timestamp
My controller extracts the data from the database and passes it to the view
public function edit($id)
{
// get the listing
$listing = DB::table('listings')
->where('listings.id', '=', $id)
->first();
$listingphone = DB::table('listings')
->leftjoin('listings_listingsphone_rel', 'listings.id', '=', 'listings_listingsphone_rel.listings_id')
->leftjoin('listingsphone', 'listings_listingsphone_rel.listingsphone_id', '=', 'listingsphone.id')
->where('listings.id', '=', $id)
->get();
// show the edit form and pass the listing
return View::make('admin.listings.edit')
->with('listing', $listing)
->with('listingphone', $listingphone);
}
Blade then needs to create multiple Input rows in the form for outputting to the screen, one for each row that exists.
{{ Form::model($listing, array('route' => array('admin.listings.update', $listing->id), 'method' => 'PUT')) }}
<div class="form-group">
{{ Form::label('listingname', 'Company Name') }}
{{ Form::text('listingname', null, array('class' => 'form-control')) }}
</div>
#foreach($listingphone as $key => $value)
<div class="form-group">
{{ Form::label('phone', 'Phone number') }}
{{ Form::text('phone', null, array('class' => 'form-control')) }}
</div>
#endforeach
{{ Form::submit('Edit the Listing!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
The problem with the code is, it will generate for me multiple Input lines with the same Name and ID
<label for="phone">Phone</label>
<input class="form-control" name="phone" type="text" id="phone">
<label for="phone">Phone</label>
<input class="form-control" name="phone" type="text" id="phone">
I obviously need to store that data in the controller with code such as this (psuedo code):-
// store
$listing = Listing::find($id);
$listing->listings_company = Input::get('listings_company');
$listing->save();
// store
$listingphone = ListingPhone::find($id);
foreach ($listingphone as $key => $value)
{
$listingphone->listings_phone = Input::get('phone['$key']');
$listingphone->save();
}
How should I be handling this type of setup within Blade/the controller?
I'm assuming that the problem you are having the text form fields is the same kind of issue that you need to deal with when you have a checkbox. You have multiple fields with the same name that needs to be referenced anyway.
For that you need to use brackets on the form field name.
You can see a similar example related to checkboxes here:
How to get the values for a series of checkboxes in Laravel 4 controller (if checked)

Resources