Laravel 4 - Many to Many - pivot table not updating - laravel

I get no obvious errors when adding a new job to my database.
My industry job goes into the jobs table but the relationship with divisions in my join table goes nowhere. I just can't see where I'm going wrong
JOIN TABLE
division_industryjob
division_id
industryjob_id
divisions
id
division_name
industryjobs
id
job_title
MODELS
Division.php
<?php
class Division extends \Eloquent {
protected $table = 'divisions';
/**
* Industry Jobs relationship
*/
public function industryjobs()
{
return $this->belongsToMany('IndustryJob');
}
}
IndustryJob.php
<?php
class IndustryJob extends \Eloquent {
protected $table = 'industryjobs';
public function divisions()
{
return $this->belongsToMany('Division');
}
}
ROUTES
Route::get('industry-jobs/add', 'AdminController#getCreateIndustryJob');
Route::post('industry-jobs/add', 'AdminController#postCreateIndustryJob')
CONTROLLER
// Create Industry - Get (empty form - new entry)
public function getCreateIndustryJob()
{
View::share('page_title', 'Create a new Industry Job Role');
View::share('sub_page_title', 'Ex: Mechanical Technician');
return View::make('admin/industry-jobs/create');
}
// Create Industry - Post
public function postCreateIndustryJob()
{
//validate user input
$rules = array(
'job_title' => 'Required|Min:3|Max:80'
);
$validation = Validator::make(Input::all(), $rules);
If ($validation->fails())
{
return Redirect::to('/admin/industry-jobs/add')->withErrors($validation);
} else {
$industryjob = new IndustryJob;
$industryjob->job_title = Input::get('job_title');
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
if (isset($input['divisions'])) {
foreach ($input['divisions'] as $divId) {
$div = Division::find($divId);
$industryjob->divisions()->save($div);
}
}
$industryjob->save();
return Redirect::to('/admin/industry-jobs')->with('message', 'Industry Job created successfully');
}
}
FORM
<form class="form-horizontal" method="post" autocomplete="off">
<!-- Industry Job Title -->
<div class="form-group">
<label class="col-md-2 control-label" for="industry_name">Industry Job Title (*)</label>
<div class="col-md-10">
<input class="form-control" type="text" name="job_title" id="job_title" value="" />
</div>
</div>
<!-- ./ Industry Job Title -->
<!-- Industry Type -->
<div class="form-group">
<label class="col-md-2 control-label" for="body">Related Division</label>
<div class="col-md-10">
<select name="divisions[]" id="divisions" size="6" class="form-control" multiple>
#foreach (Division::all() as $division)
<option value="{{ $division->id }}" >{{ $division->division_name }}</option>
#endforeach
</select>
</div>
</div>
<!-- ./ Industry Type -->
<!-- Form Actions -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-success">Create Job</button>
</div>
</div>
<!-- ./ form actions -->
</form>

You are saving the Parent model afterwards so it's not working. Save the Parent model before you save the Child Model, so it should be something like this:
$industryjob = new IndustryJob;
$industryjob->job_title = Input::get('job_title');
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
$industryjob->save();
Then save the related models using sync because it's many-to-many relationship and those related models are already created and available in the database:
if (isset($input['divisions'])) {
// Pass the array of ids to sync method
$industryjob->divisions()->sync($input['divisions']);
}
If you use the foreach loop then you may use something like this;
foreach ($input['divisions'] as $divId) {
$industryjob->divisions()->attach($divId);
}
Check more about inserting related models on Laravel website.

Related

Search Laravel Using Button

I want to search for data using a primary key, with PO as an example. Btw, I'm new to Laravel. Below is my code for my controller. I want to make the system go to the new page if the data that was searched exists(click on search button). If not, it will stay on the same page. Actually, I don't know whether my code is correct or not.
public function supplierindex(){
$supp_details = Supplier::where('PO','LIKE','%'.$searchPO.'%')->get();
return view ('frontend.praiBarcode.getweight')
->with('supp_details',$supp_details);
}
public function searchindex()
{
return view ('frontend.praiBarcode.getweight');
}
public function searchPO()
{
$searchPO = Supplier::where('PO','like',"%".$search."%")->get();
if (Supplier::where('PO','like',"%".$search."%")->exists()) {
return view('frontend.praiBarcode.getweight',compact('searchPO')); }
else {
return view('frontend.praiBarcode.index');
}
}
Below is my code in blade.php. However, the data does not come out on the screen.
<div class= "form-group">
#foreach ($supp_details as s)
<div style="font-size: 16px;" class="form-group row">
<label for="supp_name" class = "col-sm-2">PO</label>
<label for="supp_name" class = "col-sm-1">:</label>
<div class="col-sm-7">
<label> {{ $s->PO }}</label>
</div>
</div>
#endforeach
In order to pass data into the view, you have to use the second argument of the view function.
Example:
public function supplierindex(){
$supp_details = Supplier::where('PO','LIKE','%'.$searchPO.'%')->get();
return view ('frontend.praiBarcode.getweight' ,['supp_details' => $supp_details]);
}
You can use count() to check if query result is empty or not
public function searchPO()
{
$searchPO = Supplier::where('PO','like',"%".$search."%")->get();
$countsearchPO = $searchPO->count();
if ($countsearchPO ) {
return view('frontend.praiBarcode.getweight',compact('searchPO')); }
else {
return view('frontend.praiBarcode.index');
}
}
And in your blade your variable is stored in session
$supp_details = Session::get('supp_details');
#foreach ($supp_details as s)
<div style="font-size: 16px;" class="form-group row">
<label for="supp_name" class = "col-sm-2">PO</label>
<label for="supp_name" class = "col-sm-1">:</label>
<div class="col-sm-7">
<label> {{ $s->PO }}</label>
</div>
</div>
#endforeach

How can I save records in attendance table using Laravel?

I am having issue with saving attendance record of student in attendance listings. The frontend part is working well but record saved in backend of attendance table is not shown. How can I save record in backend table of attendance which consists of level_id, teacher_id and student_id
Here is my attendance migrations table
$table->id();
$table->unsignedBigInteger('level_id');
$table->unsignedBigInteger('teacher_id');
$table->unsignedBigInteger('student_id');
$table->foreign('level_id')->references('id')->on('levels');
$table->foreign('teacher_id')->references('id')->on('teachers');
$table->foreign('student_id')->references('id')->on('students');
$table->date('attendance_date');
$table->string('attendance_status');
$table->timestamps();
Here is my students migrations tables
$table->id();
// The Parents table must exist and Must have 'id' as Primary Key
$table->unsignedbiginteger('parent_id');
$table->unsignedbiginteger('level_id');
$table->foreign('parent_id')->references('id')->on('parents')
->onDelete('cascade');
$table->foreign('level_id')->references('id')->on('levels');
$table->string('student_roll_no');
$table->string('student_surname');
$table->string('student_middle_name')->nullable();
$table->string('student_given_name');
$table->string('student_place_of_birth');
$table->date('student_date_of_birth');
$table->string('student_gender');
$table->text('student_home_address');
$table->string('student_suburb')->nullable();
$table->string('student_post_code');
$table->string('student_home_phone')->nullable();
$table->string('student_work_phone')->nullable();
$table->string('student_mobile_phone');
$table->string('student_email')->nullable();
$table->string('student_photo')->nullable();
$table->string('language_spoken_at_home')->nullable();
$table->string('school_name');
$table->string('student_semester')->nullable();
$table->string('school_suburb')->nullable();
$table->text('school_address')->nullable();
$table->string('student_oversea_full_paying')->nullable();
$table->string('emergency_person_one_name')->nullable();
$table->string('emergency_person_one_mobile_number');
$table->string('emergency_person_one_house_number')->nullable();
$table->string('emergency_person_two_name')->nullable();
$table->string('emergency_person_two_mobile_number')->nullable();
$table->string('emergency_person_two_house_number')->nullable();
$table->string('medical_condition')->nullable();
$table->boolean('medical_health_support')->nullable();
$table->boolean('family_court_orders');
$table->string('family_court_file')->nullable();
$table->boolean('authority_to_school_staff');
$table->boolean('authorize_school_staff_to_arrange_medical_treatment');
$table->boolean('authorize_school_staff_administering_medication');
$table->boolean('notify_the_school_absent');
$table->boolean('withdraw_child_from_school');
$table->boolean('authorize_photograph_to_school');
$table->boolean('authorize_child_name_school_newsletter_website');
$table->boolean('authorize_short_local_walks');
$table->boolean('authorize_participate_in_any_incursions');
$table->boolean('information_contained_in_this_form_correct');
$table->boolean('status')->default(1);
$table->timestamps();
Here is my levels tables
$table->bigIncrements('id');
$table->string('level_name');
$table->timestamps();
Here is my Teachers migrations tables
$table->id();
// The Parents table must exist and Must have 'id' as Primary Key
$table->unsignedbiginteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->string('teacher_name');
$table->string('teacher_email')->unique();
$table->string('teacher_home_phone')->nullable();
$table->string('teacher_mobile_phone');
$table->string('teacher_work_phone')->nullable();
$table->string('teacher_home_address');
$table->string('teacher_suburb')->nullable();
$table->string('teacher_postcode');
$table->timestamps();
Here is my Attendance Controller
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Levels;
use App\Models\Teacher;
use App\Models\Student;
use App\Models\Attendance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class AttendanceController extends Controller
{
/**
* Create a new controller instance
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index($level_id = NULL)
{
$levels = Levels::all();
$students = Student::all();
return view('admin.attendance.list', compact( 'levels', 'students','level_id'));
}
/**
* Perform Actions in attendance.add
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function add()
{
$levels = array();
$students = array();
return view('admin.attendance.add', compact('levels', 'teachers'));
}
/**
* Store values in application dashboard
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function store(Request $request, $level_id)
{
//get form data
$data = $request->all();
//Creeate Student record
$students = Student::all();
$levels = Levels::all();
if($level_id){
$levels = Levels::find($level_id);
if($levels){
$attendance = Attendance::with(['student', 'levels'])->first();
return view('admin.attendance.add', compact('students','level_id', 'levels', 'attendance'));
}
}
}
}
Here is my Attendance model
public function student()
{
return $this->belongsTo(Student::class,'student_id');
}
public function teacher()
{
return $this->belongsTo(Teacher::class, 'teacher_id');
}
public function levels()
{
return $this->belongsTo(Levels::class, 'level_id');
}
Here is my list.blade.php file of containing attendance
#section('content')
#if(session()->has('message'))
<div class="row">
<div class="col-md-12">
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
</div>
</div>
#endif
#if(isset($levels) || $levels == '')
<div class="form-row justify-content-center">
<div class="form-group col-xs-6">
<label for="Date"> Please Select Date</label>
<input type="date" name="attendance_date" value="{{ date('Y-m-d') }}" class="form-control" required>
</div>
<div class="form-group col-xs-6">
<label for="Attendance">Please Select Level to see registered students</label>
<select class="form-control" id="level_id" name="student_id">
<option value="" disabled selected>Select Level</option>
#foreach($levels as $level)
<option value="{{#$level->id}}">{{#$level->level_name}}</option>
#endforeach
</select>
</div>
</div>
#endif
#stop
#section('js')
<script>
jQuery(document).ready(function($) {
// get your select element and listen for a change event on it
$('#level_id').change(function() {
// set the window's location property to the value of the option the user has selected
window.location = '/attendance/add/'+$(this).val();
});
});
</script>
#endsection
Here is my add.blade.php file containing attendance
<form action="{{ route('attendance.index') }}" method="GET" class="w-full max-w-xl px-6 py-12" enctype="multipart/form-data">
#csrf
#php
$heads = [
'Name',
'Roll Number',
'Semester',
['label' => 'Attendance', 'no-export' => true, 'width' => 5],
];
/*$btnDetails = '<button class="btn btn-xs btn-default text-teal mx-1 shadow" title="Details">
<i class="fa fa-lg fa-fw fa-eye"></i>
</button>';*/
$config = [
'data' => $students,
'order' => [[1, 'asc']],
'columns' => [null, null, null, null, ['orderable' => true]],
];
#endphp
{{-- Minimal example / fill data using the component slot --}}
<x-adminlte-datatable id="table6" :heads="$heads" head-theme="light" theme="light custom-head-theme dt-responsive"
striped>
#if($config['data'])
#foreach($config['data'] as $row)
<tr class="{{ (isset($row['status']) && $row['status']==0) ? 'table-danger' : ''}}">
<td>{!! $row['student_given_name'] !!}</td>
<td>{!! $row['student_roll_no']!!}</td>
<td>{!! $row['student_semester']!!}</td>
<td>
<nobr>
<select class="form-control" name="attendance_status" value="{{old('attendance_status'), #$attendance->attendance_status}}" id="attendance_status" required>
<option value="" {{#$attendance->attendance_status == '' ? 'selected' : ''}} disabled selected>Select Option</option>
<option value="Present" {{#$attendance->attendance_status == 'present' ? 'selected' : ''}} selected>Present</option>
<option value="Absent" {{#$attendance->attendance_status == 'absent' ? 'selected' : ''}}>Absent</option>
</select>
<input type="text" name="textinput" id="level_id" placeholder="Reason">
</nobr>
</td>
</tr>
#endforeach
#endif
</x-adminlte-datatable>
<div class="row mt-3">
<div class="col-md-12">
<div class="card-footer">
<div class="float-left col-md-4 mb-2">
<button type="submit" name="save_close" value="true" class="btn btn-primary btn-lg btn-block">Save & Close</button>
</div>
<div class="float-right col-md-4 mb-2">
<button type="button" class="btn btn-secondary btn-lg btn-block">Cancel</button>
</div>
</div>
</div>
</div>
</form>
#stop
What modifications are required in attendance controller in order to save record in table and I can view it on frontend side as well
On your AttendanceController you just show data, not insert data to database, you should get the request data and insert data to database, but first check your blade file, you must make an input for level_id, teacher_id, and student_id
to check your attachment you can use
dd($request);
die();
on your first line AttendanceController function store
public function store(Request $request, $level_id)
{
dd($request);
die();
//get form data
$data = $request->all();
//Create Student record
$students = Student::all();
$levels = Levels::all();
if($level_id){
$levels = Levels::find($level_id);
if($levels){
$attendance = Attendance::with(['student', 'levels'])->first();
return view('admin.attendance.add', compact('students','level_id', 'levels', 'attendance'));
}
}
}
if your system catch the good request
you should try this
public function store(Request $request, $level_id)
{
$levels_id = $request->level_id;
$teachers_id = $request->teacher_id;
$students_id = $request->student_id;
$data = [$levels_id,teachers_id,students_id];
attendance::create($data);
}
there's the code to save data into your laravel project, you should approve my solution

Laravel insert multiple records in pivot table from arrays

I'm trying to save multiple records(rows) in a table. The html fields are dynamic fields and declared as array, so they can be 1, 2 or more.
My blade:
<div class="col-md-12" id="inputFormRow" style="padding-left: 0px;">
<div class="input-group mb-3">
<input type="text" name="tableName[]" class="form-control m-input" placeholder="Name" autocomplete="off">
<input type="text" name="fromNr[]" class="form-control m-input" placeholder="From" autocomplete="off">
<input type="text" name="toNr[]" class="form-control m-input" placeholder="to" autocomplete="off">
<div class="input-group-append">
<button id="removeRow" type="button" class="btn btn-danger">X</button>
</div>
</div>
+
My JS to create dynamic fields:
$("#addRow").click(function () {
var html = '';
html += '<div class="col-md-12" id="inputFormRow" style="padding-left: 0px;">';
html += '<div class="input-group mb-3">';
html += '<input type="text" name="tableName[]" class="form-control m-input" placeholder="Name" autocomplete="off">';
html += '<input type="text" name="fromNr[]" class="form-control m-input" laceholder="From" autocomplete="off">';
html += '<input type="text" name="toNr[]" class="form-control m-input" placeholder="To" autocomplete="off">';
html += '<div class="input-group-append">';
html += '<button id="removeRow" type="button" class="btn btn-danger">X</button>';
html += '</div>';
html += '</div>';
$('#newRow').append(html);
});
My Offer.php Model:
protected $fillable = ['some columns];
public function table()
{
return $this->hasMany(Table::class);
}
My Table.php Model:
protected $fillable = ['offer_id','tableName','fromNr','toNr'];
public function offer()
{
return $this->hasMany(Offer::class);
}
Now, in my Controller, I have to get request input values and then save into Table table. The input values can be more than 1 and dynamically.
My tries:
public function store(Request $request)
{
$statement = DB::select("SHOW TABLE STATUS LIKE 'offer'");
$nextId = $statement[0]->Auto_increment;
$tableName = $request->get('tableName');
$fromNr = $request->get('fromNr');
$toNr = $request->get('toNr');
$offer = Offer::find($nextId);
$offer->table()->saveMany([
new Table(['restaurant_offer_id' => $nextId]),
new Table(['tableName' => $tableName]),
new Table(['fromNr' => $fromNr]),
new Table(['toNr' => $toNr]),
]);
}
Thank you in Advance.
If you want to make it dynamic you have to loop over the input array.
$tables = [];
foreach($tableName as $key => $value) {
$table = new Table;
$table->tableName = $tableName[$key];
$table->fromNr = $fromNr[$key];
$table->toNr = $toNr[$key];
$tables[] = $table;
}
$offer->table()->saveMany($tables);
If you use name="example[]" on the view, you are receiving the variable as an array in the controller. Also if you use Eloquent Model binding you can save the model instance to the database with simpler syntax.
Try something like this in the controller:
public function store(Request $request)
{
foreach($request->tableName as $key => $tableName)
{
Offer::create(['tableName' => $tableName',
'fromNr' => $request->fromNr[$key],
'toNr' => $request->toNr[$key]])
}
}
Additionally I recommend to use plural naming in case of arrays. Like tableNames, fromNrs. So you know that it should contain multiple variables.

Eloquent update doesn't work in Laravel 6

I'm trying to update a field after submitting in the following form:
<form action="{{ route("comments.update") }}" method="post">
#csrf
<input type="hidden" name="commentIDToEdit" id="commentID">
<div class="md-form mb-5">
<i class="fas fa-comment"></i>
<label for="toEditComment"></label>
<textarea name="toEditCommentary" id="toEditComment" cols="3" rows="5" style="resize: none"
class="form-control"></textarea>
</div>
<div class="modal-footer d-flex justify-content-center">
<button type="submit" class="btn btn-default">Modificar</button>
</div>
</form>
I have the CommentsController, where I process the data from the form. Here is the code:
public function updateComment()
{
request()->validate([
"toEditCommentary" => "min:10|max:500"
]);
if (Session::has("username") && getWarningCount(User::whereUsername(session("username"))->value("email")) > 0) {
Caveat::where("commentID", request("commentIDtoEdit"))
->update(["updatedComment" => request("toEditCommentary")]);
} else {
die("No se cumple la condiciĆ³n");
}
if (Comment::where("commentID", request("commentIDToEdit"))->exists()) {
Comment::where("commentID", request("commentIDToEdit"))
->update(["commentary" => request("toEditCommentary")]);
}
return back();
}
Curiosly, the comment is updated in his table, but not the warning. I was thinking in the fillable property in the model, but I don't have it, instead this, I have the following code:
protected $guarded = [];
const UPDATED_AT = null;
const CREATED_AT = null;
Your hidden input is named commentIDToEdit, but in the Controller you fetch the Caveat using request("commentIDtoEdit") (different case).
What you wrote:
Caveat::where("commentID", request("commentIDtoEdit"))
What you should have done: (note the different casing)
Caveat::where("commentID", request("commentIDToEdit"))
This is because in the view, the input name is commentIDToEdit, not commentIDtoEdit.

My model always give empty even I have data in database Laravel 5

UPDATE
I just found the problem here, it is typo at $instID = $request->insititution;
It should be $instID = $request->institution;
Thanks for all your helps..
UPDATE
I trying to insert to CRConfigDetail Model / table, but first I need to get my CRConfigID from CRConfig Model / Table with specific rules. So I can get the CRConfigID and put it to CRConfigDetail column.
But every time I trying to retrieve, it always give empty data even I already have data at my database. In other Controller I can retrieve data with similar rules.
Am I do something wrong with logic? Because I don't see any errors.
Here is my HTML / form:
<form action="doInsertSCC" method="POST" enctype="multipart/form-data" id="scheduleDetailForm">
{{csrf_field()}}
<div class="form-group">
<label for="institution">Institution</label>
<select name="institution" class="form-control" id="institution">
</select>
</div>
<div class="form-group">
<label for="acadCareer">Academic Career</label>
<select name="acadCareer" class="form-control" id="acadCareer">
</select>
</div>
<div class="form-group">
<label for="period">Period</label>
<select name="period" class="form-control" id="period">
</select>
</div>
<div class="form-group">
<label for="department">Department</label>
<select name="department" class="form-control" id="department">
</select>
</div>
<div class="form-group">
<label for="fos">Field of Study</label>
<select name="fos" class="form-control" id="fos">
</select>
</div>
<div class="form-group">
<label for="scc">Lecturer's ID - Name</label>
<select name="scc" class="form-control" id="scc">
</select>
</div>
<button type="submit" class="btn btn-default">Assign SCC</button>
<div id="search" class="btn btn-default">Search</div>
</form>
Here is my Route to access my Controller
Route::post('/doInsertSCC', "ScheduleController#insertSCC");
And here is my ScheduleController
public function insertSCC(Request $request){
$this->validate($request, [
'scc' => 'required'
]);
$instID = $request->insititution;
$acadID = $request->acadCareer;
$termID = $request->period;
$depID = $request->department;
$rule = ['institutionID' => $instID, 'acadCareerID' => $acadID, 'termID' => $termID, 'departmentID' => $depID];
$crConfig = CRConfig::where($rule)->first();
if( !empty($crConfig) ){
foreach ($crConfig as $cr) {
$crConfigID = $cr->CRConfigID;
}
$schedule = new CRConfigDetail;
$schedule->status = 'Pending';
$schedule->numRevision = 0;
$schedule->FOSID = $request->fos;
$schedule->SCC = $request->scc;
$schedule->CRConfigID = $crConfigID;
$schedule->save();
return redirect("AssignSCC")->with('status', 'Add SCC success!');
}else{
return redirect("AssignSCC")->with('status', 'Add schedule first!');
}
}
I already check my rules data are match with my CRConfig table's data (using console.log()
Everytime I submit this form, I will do the "else" and redirect with "Add schedule first!" message.
Actually, it does accept an array, but the array should be formatted as such..
$rule = [
['institutionID', '=', $instID],
['acadCareerID', '=', $acadID],
['termID', '=', $termID],
['departmentID', '=', $depID]
];
Source: https://laravel.com/docs/5.4/queries#where-clauses
use the below one
$crConfig = CRConfig::where('institutionID' , $instID)
->where('acadCareerID' , $acadID)
->where('termID', $termID)
->where('departmentID', $depID)
->first();
instead of
$rule = ['institutionID' => $instID, 'acadCareerID' => $acadID, 'termID' => $termID, 'departmentID' => $depID];
$crConfig = CRConfig::where($rule)->first();
You can check the query built at the backend by getting the query log, for this you have to enable the query log before the query gets built and get the query log after the query gets built both query log methods belongs to DB facade
\DB::enableQueryLog();
\DB::getQueryLog();

Resources