how to add more than one value using sync () method in laravel 5.8 - 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..

Related

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

get many to many values and which of them are selected in laravel

Contacts:
id
name
Tags:
id
name
ContactTags:
contact_id
tag_id
In Contacts model:
public function tags()
{
return $this->belongsToMany(Tags::class, "contacts_tags", "contact_id", "tag_id");
}
So if I do
$contact = Contacts::findOrFail($id);
dd($contact->tags);
I successfully get the tags associated with the contact. But how can I get all tags and a flag indicating which one of those is associated?
I'm trying to prevent fetching all tags, loop them and with each iteration loop all contact_tags and check if tag_id matches. I want to display a list of checkboxes with all tags and check the ones that are in the relation.
This code can help you, but I'm using the SELECT multiple component. You can easily adapt it to use the CHECKBOX component.
Contacts model:
public function tags()
{
return $this->belongsToMany(Tags::class, "contacts_tags", "contact_id", "tag_id");
}
ContactController.php
public function edit(Contact $contact)
{
$tags = Tag::all();
return view('contacts.edit',compact('contact', 'tags'));
}
edit.blade.php
<div class="row">
<div class="col">
<div class="form-group">
<strong>Tags:</strong>
<select name="tags_id[]" multiple>
#foreach ($tags as $tag)
#if( $contact->tags->contains($tag) )
<option value="{{ $tag->id }}" selected>{{ $tag->name }}</option>
#else
<option value="{{ $tag->id }}">{{ $tag->name }}</option>
#endif
#endforeach
</select>
</div>
</div>
</div>
Update in ContactController.php
public function update(Request $request, Post $contact)
{
$validatedData = $request->validate([
'tags_id' => ['array'],
]);
$contact->update($request->all());
$contact->tags()->sync($validatedData['tags_id']);
return redirect()->route('contact.index')->with('success', 'Contact successfully updated!');
}
The validation is just an example. The $validatedData has no use here, but it can be used to update the contact if you validate the other fields.

How to send variable from blade to controller without changing the url

In blade I have a list of books. I want to choose a specific book to show its information. And to do so I want to send with href the id of the book to my controller passing through route.
For example i have
<div class="body text-center">
<h6><b>{{($book->getName())}}</b></h6>
</div>
In href I want to add $bookId = $book->id and the route name so I can call the route with the specific name which calls a method in a controller which can use the variable $bookId
Route::get('/infromation','Books\BookController#index')->name('info');
Here's two propositions:
The first one is to use spatie/laravel-sluggable to have the book name in the URL
The second one is to access the book without changing the URL with a POST request
Using spatie/laravel-sluggable
The slug will be generated automatically from name when the book is created.
your-migration.php
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('slug')->unique()->index();
$table->string('name');
// ...
$table->timestamps();
});
web.php
// Change the URIs as you want. `{book}` is mandatory to retrieve the book though.
Route::get('/books','Books\BookController#index')->name('book.index');
Route::get('/books/{book}','Books\BookController#show')->name('book.show');
Book.php
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class Book extends Model
{
use HasSlug;
protected $guarded = [];
public function getSlugOptions()
{
// Adapt with what you want
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->doNotGenerateSlugsOnUpdate();
}
public function getRouteKeyName()
{
return 'slug';
}
}
BookController.php
class BookController extends Controller
{
public function index()
{
return view('book.index');
}
public function show(Book $book)
{
// $book is retrieving using Model Binding: https://laravel.com/docs/5.8/routing#route-model-binding
return view('book.show', compact('book'));
}
}
index.blade.php
<div class="body text-center">
<a href="{{ route('book.show', $book) }}">
<h6><b>{{ $book->getName() }}</b></h6>
</a>
</div>
Using POST request (URI does not change) and without SLUG
I wouldn't recommend using this for the user experience.
The user cannot bookmark the book or share the link with someone else
When refreshing the page, it will prompt to the user if he want to re-submit the form request
web.php
Route::get('/books','Books\BookController#index')->name('book.index');
Route::post('/books','Books\BookController#show')->name('book.show');
BookController.php
class BookController extends Controller
{
public function index()
{
return view('book.index');
}
public function show()
{
$book = Book::findOrFail(request('book_id'));
return view('book.show', compact('book'));
}
}
index.blade.php
<div class="body text-center">
<form action="{{ route('book.show') }}" method="POST">
#csrf
<input type="hidden" value="{{ $book->id }}" name="book_id">
<h6>
<button type="submit">
<b>{{ $book->getName() }}</b>
</button>
</h6>
</form>
</div>
You can remove the default button style to make it looks like a link
https://stackoverflow.com/a/45890842/8068675
You can try like this
<form action="/BookName/information/<?php echo $book->id; ?>" method="post">
<div class="body text-center">
<input type="hidden" name="book_id" value="{{ $book->id }}">
<a href="/information/<?php echo $book->id; ?>">
<button type="submit" name="book_information" class="btn btn-primary">
<h6>
<b>{{($book->getName())}}</b>
</h6>
</button>
</div>
</form>
// make route like this
Route::post('/BookName/information/{id}','Books\BookController#index');
// Access the that id in controller
public function index(Request $request)
{
echo $request->book_id;
}

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.

Resources