How to save multiple Checkboxes value into Pivot Table? - php

I have 2 models with Many-to-Many Relation when I create new Device and check multiple Checkboxes I want to save multiple voices_id with Device_id into the Pivot Table device_voice
Device Controller ( I am facing this error Undefined variable: selectedVoice in Edit function )
public function create()
{
$this->authorize("create", Device::class);
$voice_list = Voice::all();
return view('devices.create')
->with('voice_list', $voice_list);
}
public function store(CreateDeviceRequest $request)
{
$this->authorize("create", Device::class);
$input = $request->all();
$voices_checkbox = $input['voice'];
$device = $this->deviceRepository->create($input);
//Device Id and Selected voices is Saved Successfully
$device ->voices()->sync($voices_checkbox);
Flash::success('Device saved successfully.');
return redirect(route('devices.index'));
}
public function edit($id)
{
$device = $this->deviceRepository->findWithoutFail($id);
$this->authorize("update", $device);
$voice_list = Voice::all();
// Here I am getting Device's checked voices, but sinces I am sharing the same Fields Blade with Create and Edit I get this error
//Undefined variable: selectedVoice
$selectedVoice = $device->voices->pluck("id")->toArray();
if (empty($device)) {
Flash::error('Device not found');
return redirect(route('devices.index'));
}
return view('devices.edit')
->with('device', $device)
->with('voice_list', $voice_list)
->with('selectedVoice', $selectedVoice);
}
This is My Fields for Both Create and Edit Views
<!-- Device Number Field -->
<div class="form-group col-sm-6">
{!! Form::label('device_number', 'Device Number:') !!}
{!! Form::text('device_number', null) !!}
</div>
<!-- Batch Field -->
<div class="form-group col-sm-6">
{!! Form::label('device_name', 'Device Name:') !!}
{!! Form::text('device_name', null) !!}
</div>
<!-- Batch Field -->
<div class="form-group col-sm-6">
{!! Form::label('voices_id', 'Voices:') !!}
#foreach ($voice_list as $voice)
{!! Form::checkbox('voice[]', $voice->id, in_array($voice->id, $selectedVoice)) !!}
{!! Form::label('voice', $voice->name) !!}
#endforeach
</div>
<!-- Version Field -->
<div class="form-group col-sm-6">
{!! Form::label('version', 'Version:') !!}
{!! Form::text('version', null) !!}
</div>
Thanks!

Use the sync() method:
$device->voices()->sync($request->voices);

Related

Laravel how to echo selected a value in a dropdown using blade when updating a specific resource

I want to echo the selected value when I edit a specific resource in my table. When I edit the specific resource it should display the current data in my dropdown but in the real scenario it displays the first one on the list which is wrong. So how can I echo the selected value in the options of the dropdown using blade in laravel?
Here is some sample of my code in the view below
<!-- Shows Field -->
<div class="form-group col-sm-6">
{!! Form::label('show_id', 'Shows:') !!}
{!! Form::select('show_id', $shows, $shows, ['class' => 'form-control input-md','required'])!!}
</div>
{{-- {{ $channelshows->channel->name }} --}}
<!-- Client Id Field -->
<div class="form-group col-sm-6">
{!! Form::label('channel_id', 'Channels:') !!}
{!! Form::select('channel_id', $channel, $channel, ['class' => 'form-control input-md','required'])!!}
</div>
<!-- Submit Field -->
<div class="form-group col-sm-12">
{!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
Cancel
</div>
and here is the code in my controller below.
public function edit($id)
{
$channelshows = $this->channelshowsRepository->findWithoutFail($id);
$shows = Show::pluck('name', 'id');
$channel = Channel::pluck('name', 'id');
if (empty($channelshows)) {
Flash::error('Assigned show not found');
return redirect(route('admin.channelshows.index'));
}
return view('admin-dashboard.channelshows.edit', compact('shows', $shows), compact('channel', $channel))->with('channelshows', $channelshows);
}
Everything here works fine even if I updated the specific resource. I just want to auto populate or select the current value of the resource that I will update because when I edit the specific resource it shows the first one on the list.
Am I going to use an #if statement in blade? But how can I do it using the blade template in my select form. Can somebody help me?
Appreciate if someone can help.
Thanks in advance.
Here is an example:
Open form:
{{ Form::model($service, array('route' => array('services.update', $service->id))) }}
Select form field:
<div class="form-group">
{{ Form::label('Related Agreement') }}
{{ Form::select('agreement', $agreementsList, null, array('class'=>'form-control', 'placeholder'=>'Please select ...')) }}
</div>
In Controller:
$agreementsList = Agreement::all()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)->pluck('name', 'id');
(Include this when passing data to your view)

Laravel post form error

I'm having a problem for the first time when i submit a form.
When i submit the form it doesn't go to post route and i don't know why.
my post route is that:
Route::post('/app/add-new-db', function()
{
$rules = array(
'name' => 'required|min:4',
'file' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
// redirect our user back to the form with the errors from the validator
return Redirect::to('app/add-new-db')
->withErrors($validator);
}
else
{
$name = Input::get('name');
$fname = pathinfo(Input::file('file')->getClientOriginalName(), PATHINFO_FILENAME);
$fext = Input::file('file')->getClientOriginalExtension();
echo $fname.$fext;
//Input::file('file')->move(base_path() . '/public/dbs/', $fname.$fext);
/*
DB::connection('mysql')->insert('insert into databases (name, logotipo) values (?, ?)',
[$name, $fname.$fext]);
*/
//return Redirect::to('app/settings/');
}
});
And my html:
<div class="mdl-cell mdl-cell--12-col content">
{!! Form::open(['url'=>'app/add-new-db', 'files'=>true]) !!}
<div class="mdl-grid no-verticall">
<div class="mdl-cell mdl-cell--12-col">
<h4>Adicionar Base de Dados</h4>
<div class="divider"></div>
</div>
<div class="mdl-cell mdl-cell--6-col">
<div class="form-group">
{!! Form::label('name', 'Nome: ') !!}
{!! Form::text('name', null, ['id'=> 'name', 'class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('image', 'Logotipo:') !!}
{!! Form::file('image', ['class'=>'form-control']) !!}
#if ($errors->has('image'))
<span class="error">{{ $errors->first('image') }}</span>
#endIf
</div>
<div class="form-group">
{!! Form::submit('Adicionar', ['id'=>'add-new-db', 'class'=>'btn btn-default']) !!}
<p class="text-success"><?php echo Session::get('success'); ?></p>
</div>
</div>
</div>
{!! Form::close() !!}
</div>
I'm loading this from from a jquery get:
function addDB()
{
$( "#settings-new-db" ).click(function(e)
{
$.get('/app/add-new-db', function(response)
{
$('.content-settings').html("");
$('.content-settings').html(response);
componentHandler.upgradeDom();
});
e.preventDefault();
});
}
When i try to submit the form i'm getting 302 found in network console from chrome.
I'm doing forms at this way and it is happens for the first time. Anyone can help me?
Thanks
Fix the name attribute for your image upload field. You refer it as image in the form but you are trying to fetch it as file in your controller.

Getting information from one table and saving the returned information in new table - Laravel 5.2

I'm making a school system for my school and I have this problem in which I'm stuck for days. In my app I have users with type admin, teacher and student. The admin creates all the users and all the other information. Now I'm making the teacher panel in which the teacher will be able to add marks for the students and later they will be displayed in the student panel.
So in first place when the teachers get into their account he will be able to pick a class which he teaches and the subjects which he teaches, for that case I have table - class_subjects in which I'm saving the teacher_id, subject_id and class_id from the admin panel. I'm calling this here, in my teacher panel, and it seems to work just fine, because I see the exact classes and subjects I need. After that I need to make a post query with these both picked from the teacher and in return to get all the students from the picked class + the picked subject, that also works exactly how I want it. So what I am returning is a new blade with arrays with information from the table class_subject, from this returned arrays the teacher need to pick information, and here in text field he must add his mark for the student he picks. After that I need to save the picked information in new table called student_marks with fields student_id, subject_id, mark_type_id, mark.
My question is how the save this information (that the teacher picks) in the new table (student_marks)?
I'm posting the controller:
class AccountController extends Controller
{
public function getIndex() {
$user = Auth::user();
$classStudent = ClassSubject::where('teacher_id','=',$user->id)->get()->lists('class_id');
$userSubject = ClassSubject::where('teacher_id','=',$user->id)->get()->lists('subject_id');
return view('educator.account.account',[
'user' => $user,
'userTeacher'=> $classStudent,
'userSubject'=> $userSubject,
]);
}
public function postIndex(Request $request) {
ClassSubject::where(
'subject_id','=',$request->get('userSubject'),
'class_id','=',$request->get('userClass')
);
$user = Auth::user();
$markType = MarkType::lists('type');
$sub = Subject::where('id','=',$request->get('userSubject'))->get()->lists('name');
$stu = User::where('class_id','=',$request->get('userClass'))
->orderBy('first_name', 'asc')->get()->lists('full_name');
return view('educator.account.input', [
'user' => $user,
'studentss'=> $stu,
'markType' => $markType ,
'sub'=> $sub,
}
I know its a bit twisted but I'm really stuck in here and I will be really grateful if someone can finally help me with this. If something is unclear, please ask.
educator.account.account (first blade)
#extends('teacher-app')
#section('teacher-content')
<div class="col-md-6">
{!! Form::open(['method' => 'post', 'class' => 'form-horizontal']) !!}
<div class="form-group">
{!! Form::label('profile_id','Избери клас:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('userClass', $userTeacher, null, ['class'=>'form-control']) !!}
</div>
</div>
<br>
<div class="form-group">
{!! Form::label('profile_id','Избери предмет:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('userSubject', $userSubject, null, ['class'=>'form-control']) !!}
</div>
</div>
<div align="center">
{!! Form::submit('Избери', ['class' => 'btn btn-default']) !!}
</div>
{!! Form::close() !!}
#stop
</div>
educator.account.input (second blade)
#extends('teacher-app')
#section('teacher-content')
<div class="col-md-8">
{!! Form::open(['method' => 'post', 'class' => 'form-horizontal']) !!}
<div class="form-group">
{!! Form::label('profile_id','Ученик:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('userStu', $studentss, null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile_id','Оценка:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-2">
{!! Form::text('mark',null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile_id','Тип оценка:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('markType', $markType, null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile_id','Предмет:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('stuSub', $sub, null, ['class'=>'form-control']) !!}
</div>
</div>
<br>
<div align="center">
<button type="button" class="btn btn-default">Назад</button>
{!! Form::submit('Запиши', ['class' => 'btn btn-default']) !!}
</div>
{!! Form::close() !!}
</div>
#stop
When they submit the form for the student rating, you'll have a route similar to this to post to:
class AccountController extends Controller {
public function markStudent(Request $request)
{
// get request data
$mark = $request->input('mark');
$subject_id = $request->input('stuSub');
$mark_type = $request->input('markType');
$student_id = $request->input('userStu');
// get the existing record or create a new, empty record
$student_mark = StudentMark::firstOrNew(compact('student_id', 'subject_id'));
// add the updated data to the model
$student_mark->fill(compact('mark_type', 'mark'));
// persist to database
$student_mark->save();
// redirect or do whatever you want after request completion...
}
}
This above code assumes you only want one entry per student, per subject (ie. a unique index on both these columns).
I would also recommend that you validate the data before inserting it, either by doing so before the StudentMark::firstOrNew() or by creating a custom request object with validation.

Laravel: How to bind form data

Scenario:
I have a form for each subject and each subject have three or four questions and the user have to answer those question then save the data on the database
The problem:
How to bind the data with the form so the form refilled with the data that inputted before by the user.
I have tried a lot and search a lot to find a solution but I didn't find anything useful.
Code:
Controller:
public function saveData(Request $request, $user_id, $subject_id)
{
$all_data = $request->input('row');
foreach ($all_data as $data) {
$question_id = $data['question_id'];
$check_data = ['user_id' => $user_id, 'question_id' => $question_id, 'subject_id' => $subject_id];
$exist_data = RatingDatum::where($check_data)->get()->first();
if (is_null($exist_data)) {
RatingDatum::create($data);
} else {
$save = RatingDatum::findorfail($exist_data->id);
$save->update($data);
}
}
flash()->success('Data has been submitted.');
return 'done';
}
View :
<div class="row">
{!! Form::model(['method' => 'PATCH','action'=>['RatingDataController#saveData'],$organisation->id,$organisation->sector->id]) !!}
<div class=" col-md-9">
<h3> {{$subject_name->subject}}</h3>
#foreach($question as $index=>$question)
<div class="plan bg-plan">
<h5>{{$question->question}}</h5>
<hr>
<!-- create sector form -->
#foreach($answers as $answer)
<div class="radio">
<label>
{!! Form::radio('row['.$index.'][answer_id]', $answer->id,true)!!}
{{$answer->answer}}
</label>
</div>
#endforeach
<div class="form-group">
{!! Form::label('comment','Comment :') !!}
{!! Form::textarea('row['.$index.'][comment]' ,null,['class'=>'form-control', 'rows' => 4]) !!}
</div>
</div>
#endforeach
</div>
{!! Form::submit('Submit Data', ['class' => 'btn btn-success submit right']) !!}
{!! Form::close() !!}
</div>

How to save uploaded file name in table using Laravel 5.1

I need help in saving uploaded file name in database table using laravel 5.1.
My Controller code for saving Image details
public function store(Request $request)
{
if($request->hasFile('img_filename'))
{
$destinationPath="offerimages";
$file = $request->file('img_filename');
$filename=$file->getClientOriginalName();
$request->file('img_filename')->move($destinationPath,$filename);
}
$input=$request->all();
Offer_image::create($input);
return redirect('offerimage');
}
My view code for accepting image
{!! Form::open(array('route'=>'offerimage.store','role'=>'form','files'=>true)) !!}
<div class="box-body">
<div class="form-group">
{!! Form::label('img_name','Name') !!}
{!! Form::text('img_name', $value = null, $attributes = array('class'=>'form-control','id'=>'img_name','required')) !!}
</div>
<div class="form-group">
{!! Form::label('img_description','Description') !!}
{!! Form::textarea('img_description', $value = null, $attributes = array('class'=>'form-control','id'=>'img_description','required')) !!}
</div>
<div class="form-group">
{!! Form::label('img_filename','Upload Image') !!}
{!! Form::file('img_filename') !!}
</div>
{!! Form::hidden('status',$value='active') !!}
</div><!-- /.box-body -->
<div class="box-footer">
{!! Form::submit('Submit',$attributes=array('class'=>'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
This controller code to store image working properly, but where i am trying to save image file name to table , this code is storing filepath to database table.
As I am using direct create() method to store the request object in table, I don't know how do I store file name instead of path.
Check this Image for table data
The Problem is that your Request Data hasn't changed while you uploaded the picture. So img_filename still contains tmpdata.
You can try this:
$input = $request->all();
$input['img_filename'] = $filename;
Code that works for me :
$updir = 'images/';
$img_name = 'image.jpeg';
Request::file('img_filename')->move($updir, $img_name);
$file = $request->file('img_filename');
$filename=$file->hashName();
Above is the hash name Laravel uses to save your files

Categories