Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidtrushkov/22da0791e5cb757ec58579b9075296af to your computer and use it in GitHub Desktop.
Save davidtrushkov/22da0791e5cb757ec58579b9075296af to your computer and use it in GitHub Desktop.
Add multiple select tagging in Laravel 5.5 with Select2. Can be reused with different models. Also keeps old data selected on reload and on edit.
// The taggable database table
public function up() {
Schema::create('stateables', function (Blueprint $table) { // In this case taggables
$table->increments('id');
$table->string('stateables_type'); // In this case taggable_type
$table->integer('stateables_id')->unsigned(); // In this case taggables_id
$table->integer('state_id')->unsigned(); // In this case tag_id
$table->timestamps();
});
}
// This is the Tag model
class Tag extends Model {
protected $fillable = ['name'];
// This is a refrence to a diffrent model that has many tags
public function lawyers() {
return $this->morphedByMany(Lawyer::class, 'taggable');
}
}
// This is an example model where it has many tags.
class Lawyer extends Model {
public function tags() {
return $this->morphToMany(Tag::class, 'taggables');
}
}
// Th is used in front end to get old data selected from dropdown and keep old data when on page refresh
function isSelected($id){
if(!($ids=old('state_tags_id'))){
$ids = $this->tags->pluck('id');
}
return collect($ids)
->contains($id) ? 'selected' : '';
}
// This is the create/edit select dropdown with muitple select
<select name="state_tags_id[]" class="form-control state-tags-multiple" multiple="multiple">
@foreach(\App\Tag::all() as $$tag)
<option value="{{ $tag->id }}" {{ $lawyer->isSelected($tag->id) }}>
{{ $tag->name }}
</option>
@endforeach
</select>
<script type="text/javascript">
$(".state-tags-multiple").select2({
placeholder: "Select a state",
});
</script>
// This is to store method to save all the tags in table
public function store(Request $request) {
$this->validate($request, [
'name' => 'required|string|max:255',
]);
$lawyer = Lawyer::create([
'name' => request('name')
]);
// Attach all the tags to this lawyer
$lawyer->tags()->sync($request->state_tags_id);
$lawyer->save;
return redirect(route('lawyers.index'));
}
// This the update method to update tags in database table
public function update(Request $request, $id) {
$this->validate($request, [
'name' => 'required|string|max:255'
]);
$lawyer = Lawyer::where('id', $id)->first();
$lawyer->name = $request->name;
$lawyer->tags()->sync($request->state_tags_id);
$lawyer->save;
return redirect(route('lawyers.index'));
}
// And this is to deletwe the tags when the model is deleted
public function destroy(Lawyer $lawyer) {
try {
$lawyer->tags()->sync([]);
$lawyer->delete();
} catch (\Exception $e) {
return back();
}
return back();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment