I'm trying to insert entries in database table but it's not working. It was working 2 weeks ago but I thing I have accidentally changed something.
my relevant model, migration and controllers are here
Model - Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
//
protected $table='profile';
protected $fillable=['user_id', 'Gender', 'Age', 'Address'];
}
Migration -
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfileTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::create('profile', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->char('Gender', 1);
$table->string('Age')->unique();
$table->string('Address');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
Controller - profileController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Profile;
use App\Http\Requests;
use Request;
use Carbon\Carbon;
//use App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
class profileController extends Controller
{
//
public function index(){
return view('pages.profile');
}
public function store(){
$uid=Auth::user()->id;
$input=Request::all();
$input['user_id']=$uid;
$profile = new Profile(array('user_id'=>$uid, 'gender'=>$input['gender'], 'age'=>$input['age'], 'address'=>$input['address']));
return view('welcome');
}
}
The page with form - pages/profile.blade.php
{!! Form::open(array('class' => 'form-horizontal col-xs-10 col-sm-6 col-md-4')) !!}
<!-- <form class="form-horizontal col-xs-10 col-sm-6 col-md-4 ">-->
<fieldset>
<!-- Form Name -->
<legend>User Profile</legend>
<!-- Multiple Radios -->
<div class="form-group">
<label class="col-md-4 control-label" for="gender">Gender</label>
<div class="col-md-4">
<div class="radio">
<label for="gender-0">
<input type="radio" name="gender" id="gender-0" value="1" checked="checked">
Male
</label>
</div>
<div class="radio">
<label for="gender-1">
<input type="radio" name="gender" id="gender-1" value="2">
Female
</label>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="age">Age</label>
<div class="col-md-2">
<input id="age" name="age" type="text" placeholder="Age" class="form-control input-md">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="address">Address</label>
<div class="col-md-8">
<textarea class="form-control" id="address" name="address">Address</textarea>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<button id="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
<!--</form>-->
{!! Form::close() !!}
Also, just in case, my route.php -
Route::get('profile', 'profileController#index');
Route::post('profile', 'profileController#store');
In your migration, you use uppercase column names (i.e. "Gender"), whereas you use lowercase ("gender") when you try to fill your model. Also, you never save your model:
$profile = new Profile(array('user_id'=>$uid, 'Gender'=>$input['gender'], 'Age'=>$input['age'], 'Address'=>$input['address']));
$profile->save(); // <- You need to call save() to persist the model to your database.
return view('welcome');
Under: $profile = new Profile(array('user_id'=>$uid, 'gender'=>$input['gender'], 'age'=>$input['age'], 'address'=>$input['address']));
wrtite : $profile->save();
and the action? of {!! Form::open(array('class' => 'form-horizontal col-xs-10 col-sm-6 col-md-4')) !!}
read this http://laravelcollective.com/docs/5.1/html#form-model-binding
Related
This is my code in blade
<div class="col-lg-6">
<div class="contact-form">
<form id="contact" action="{{url('/reservation')}}" method="post">
#csrf
<div class="row">
<div class="col-lg-12">
<h4>Reservation</h4>
</div>
<div class="col-lg-6 col-sm-12">
<fieldset>
<input name="name" type="text" id="name" placeholder="Your Name*" >
</fieldset>
</div>
<div class="col-lg-6 col-sm-12">
<fieldset>
<input name="email" type="text" id="email" pattern="[^ #]*#[^ #]*" placeholder="Your Email Address" >
</fieldset>
</div>
<div class="col-lg-6 col-sm-12">
<fieldset>
<input name="phone" type="number" id="phone" placeholder="Phone Number*" >
</fieldset>
</div>
<div class="col-md-6 col-sm-12">
<input type="text" name="address" placeholder="Address">
</div>
<div class="col-lg-6">
<div id="filterDate2">
<div class="input-group date" data-date-format="dd/mm/yyyy">
<input name="date" id="date" type="text" class="form-control" placeholder="dd/mm/yyyy">
<div class="input-group-addon" >
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</div>
<div class="col-md-6 col-sm-12">
<input type="time" name="time">
</div>
#foreach($data as $data)
<div class="row">
<div class="col-sm-3">
<p class='mybox text-dark'><input type="checkbox" name="productz[]" value="{{$data->title}}"/>{{$data->title}}</p>
</div>
#endforeach
</div>
<div class=" col-lg-12 mt-5">
<fieldset>
<button type="submit" id="form-submit" class="main-button-icon">Make A Reservation</button>
</fieldset>
</div>
</div>
</form>
</div>
</div>
THIS IS WHAT'S INSIDE MY MODEL
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Reservation extends Model
{
use HasFactory;
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Reservation extends Model
{
use HasFactory;
}
FOR MY CONTROLLER
$reservation = new reservation();
$reservation->productz= implode(", " ,$request->productz);
$reservation->save();
return view('reservation');
}
FROM MY MIGRATED TABLE
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateReservationsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('email')->nullable();
$table->string('phone')->nullable();
$table->string('address')->nullable();
$table->string('date')->nullable();
$table->string('time')->nullable();
$table->string('productz')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('reservations');
}
}
Tried to look for tutorial similar to what I'm doing where I retrieved the data from the database such as title and inserted it to checkbox which is successfully displayed. But I can't insert the data checked into the database.
You should use the with function, which adds a piece of data into your view, in conjunction with the view function.
So something like:
return view('reservation')->with('data', $reservation->productz);
should work. Also do make sure the name of each variable that you're looping over is different from the name of the array itself -> e.g. foreach($datum as $data).
Try to print_r($request->productz) and look the data from checkedbox is printing the correct data or not
I am new to Laravel and I am using Laravel 9. I am creating a migraine diary web app. I managed to create a custom log in and register system and created a page to display the diary entries and a diary entry form. Currently that page shows the username and user id with a couple of other lines. For showing the diary entries, I am currently trying to show the diary date to get it working, once I can show the date, I should be able to show the rest.
However, after completing the form I am redirected to the diary page as intended but the date from the database is not showing. I checked tinker and the data is being stored and when I used ddd it seems that no data is being sent to the view so I suspect it is something to do with how I am passing data into the view
I currently have 2 controllers, one to handle get requests so as to control user authorisation (and post requests for log in and register) and the other for post requests not related to log in and registration.
The relationship between users and the diary is that a user can have many diary entries, while a diary can only have one user
this is what shows at the bottom of ddd()
snip of bottom of ddd
routes (web.php)
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthorisationController;
use App\Http\Controllers\EntryController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('diary', [AuthorisationController::class, 'diary'])->name('diary');
Route::get('loginpage', [AuthorisationController::class, 'loginPage'])->name('loggingin');
Route::post('computeLogin', [AuthorisationController::class, 'completeLogin'])->name('login.custom');
Route::get('register', [AuthorisationController::class, 'registerPage'])->name('registerUser');
Route::post('computeRegister', [AuthorisationController::class, 'computeRegistration'])->name('register.compute');
Route::get('signout', [AuthorisationController::class, 'logOut'])->name('logout');
Route::get('/addDiary', [AuthorisationController::class, 'addDiary'])->name('addDiary');
Route::post('/addDiary/entry', [EntryController::class, 'addDiaryEntry'])->name('addDiaryEntry');
User model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'username',
'password',
];
public $timestamps = false;
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password'
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
];
public function diaries()
{
return $this->hasMany(Diary::class);
}
}
Diary model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Diary extends Model
{
use HasFactory;
protected $fillable = [
'date',
'user_id',
'stress',
'low_water_intake',
'chocolate',
'cheese',
'yeast_goods',
'yoghurt',
'fruit',
'nuts',
'olives',
'tomato',
'soy',
'vinegar',
'medication',
'comment'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
Authorisation Controller
<?php
/*
need to customise look
check for other bugs
*/
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use App\Models\User;
use App\Models\Diary;
use Illuminate\Support\Facades\Auth;
class AuthorisationController extends Controller
{
# index
public function loginPage()
{
return view('auth.loginpage');
}
# customLogin
public function completeLogin(Request $request)
{
$request->validate([
'username' => 'required',
'password' => 'required',
]);
$successful = 'Welcome User!';
$failedLogin = 'Error! Entered details are not valid, please try again or register an account!';
# diary
$verifications = $request->only('username', 'password');
if (Auth::attempt($verifications)) {
return redirect('diary')->with('success', $successful);
}
return redirect('loginpage')->with('failed', $failedLogin);
}
# registration
public function registerPage()
{
return view('auth.registerpage');
}
public function computeRegistration(Request $request)
{
$request->validate([
'username' => 'required|unique:users',
'password' => 'required|min:6',
'password1' => 'required|min:6',
]);
$info = $request->all();
if($info['password'] == $info['password1']){
User::create([
'username' => $info['username'],
'password' => Hash::make($info['password'])
]);
$successRegistration = 'You have created an account!';
$verifications = $request->only('username', 'password');
if (Auth::attempt($verifications)) {
return redirect('diary')->with('successReg', $successRegistration);
}
} else {
$notMatching = 'Passwords do not match';
return redirect('register')->with('notMatching', $notMatching);
}
}
public function diary(User $user){
if(Auth::check()){
ddd('wont show data', $user->diaries);
$data = $user->diaries->all();
return view('diary', [
'diaries' => $data,
]);
}
$noAccess = 'You are not signed in, either sign in or register!';
return redirect('loginpage')->with('noAccess', $noAccess);
}
public function addDiary()
{
if(Auth::check()){
return view('addDiary');
}
$noAccess = 'You are not signed in, either sign in or register!';
return redirect('loginpage')->with('noAccess', $noAccess);
}
public function logOut(){
Session::flush();
Auth::logout();
$loggedOut = 'You have logged out, want to log back in?';
return redirect('loginpage')->with('loggedOut', $loggedOut);
}
}
Entry Controller (this controls posts not related to log in and register)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Diary;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
class EntryController extends Controller
{
public function addDiaryEntry(Request $request)
{
$rules = [
'date' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if($validator->fails())
{
return redirect()->back();
}
$data = $request->all();
$diaryEntry = new Diary();
$diaryEntry->user_id = Auth::user()->id;
$diaryEntry->date = $data['date'];
$diaryEntry->stress = $data['stress'];
$diaryEntry->low_water_intake = $data['dehydrated'];
$diaryEntry->chocolate = $data['chocolate'];
$diaryEntry->cheese = $data['cheese'];
$diaryEntry->yeast_goods = $data['yeast'];
$diaryEntry->yoghurt = $data['yoghurt'];
$diaryEntry->fruit = $data['fruit'];
$diaryEntry->nuts = $data['nuts'];
$diaryEntry->olives = $data['olives'];
$diaryEntry->tomato = $data['tomato'];
$diaryEntry->soy = $data['soy'];
$diaryEntry->vinegar = $data['vinegar'];
$diaryEntry->medication = $data['takenMeds'];
$diaryEntry->comment = $data['comment'];
if (!$diaryEntry->save())
{
return redirect()->back();
}
$diaryEntry->save();
return redirect('diary');
}
}
dairy.blade.php
#extends('layout')
#section('maincontent')
<main>
#foreach ($diaries as $diary)
<div class="container">
<h4>
Date
</h4>
<p>
{{ $diary->date->toDateString() }}
</p>
</div>
#endforeach
<p>
Welcome {{ auth()->user()->username }}!
</p>
<p>
Welcome user with id {{ auth()->user()->id }}!
</p>
#if (session('success'))
<small>
{{ session('success') }}
</small>
#elseif (session('successReg'))
<small>
{{ session('successReg') }}
</small>
#endif
<p style="margin:1em;">
Success.
</p>
<button>
Add Diary Entry
</button>
</main>
#endsection
addDiary.blade.php
#extends('layout')
#section('maincontent')
<main>
<div class="container">
<form method="POST" action="{{ route('addDiaryEntry') }}">
#csrf
<div class="form-group row">
<label for="text" class="col-4 col-form-label">Date</label>
<div class="col-8">
<input id="date" name="date" type="date" class="form-control" required="required">
</div>
</div>
<div class="form-group row">
<label class="col-4">Stressed</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="stress" id="stress" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Dehydrated</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="dehydrated" id="dehydrated" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Chocolate</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="chocolate" id="chocolate" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Cheese</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="cheese" id="cheese" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Yeast Products</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="yeast" id="yeast" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Yoghurt</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="yoghurt" id="yoghurt" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Citrus Fruits</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="fruit" id="fruit" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Nuts</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="nuts" id="nuts" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Olives</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="olives" id="olives" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Tomato</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="tomato" id="tomato" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Soy</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="soy" id="soy" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Vinegar</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="vinegar" id="vinegar" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label for="takenMeds" class="col-4 col-form-label">Medication Taken</label>
<div class="col-8">
<textarea id="takenMeds" name="takenMeds" cols="40" rows="5" class="form-control"></textarea>
</div>
</div>
<div class="form-group row">
<label for="comments" class="col-4 col-form-label">Comment</label>
<div class="col-8">
<textarea id="comments" name="comment" cols="40" rows="5" class="form-control"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-4 col-8">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</main>
#endsection
So i was trying to make a posting form using ckeditor and post it to database, and then try to display it in the same view, but after i submit the form i don't see anything in my database table so clearly it's not even storing to database, is there any mistakes in my controller or view ?
this is my GuestbookController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Guestbook;
class GuestbookController extends Controller
{
public function index()
{
$guestbooks = Guestbook::get();
return view('post.post_textarea',[
'guestbooks' => $guestbooks,
]);
}
public function store(Request $request)
{
Guestbook::create([
'name' => $request->name,
'message' => $request->message
]);
return redirect()->back();
}
}
this is my routes
Route::get('/posting','GuestbookController#index')->name('guestbook');
Route::post('/posting','GuestbookController#store')->name('guestbook.store');
this is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Guestbook extends Model
{
protected $fillable = ['name', 'message'];
}
and this is my view
<section class="games-single-page">
<div class="container">
#foreach ($guestbooks as $guestbook)
<div class="card">
<div class="card-body">
<label>mike</label>
<h3>{{ $guestbok->name }}</h3>
{!! $guestbook->message !!}
</div>
</div>
#endforeach
<div class="card">
<div class="card-body">
<form action="/posting" method "POST">
<div class="form-group">
<label style="color: black;" >Title</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label style="color: black;" >Your Input</label>
<br>
<textarea class="form-control" name="message" id="" rows="10"></textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value"Send">
</div>
</form>
</div>
</div>
</div>
</section>
You forgot an equal sign '=' and a csrf field. try the answer.
<form action="/posting" method="POST">
{{csrf_field()}}
I created an edit form to update values in my database and then show it on the main page. The problem is that it doesn't save the data to DB.
the request passes: Status Code: 302 Found
with all the values that I want to change (for example adding phone and mail):
effective_date_practitioner: 2019-01-01
expiry_date_practitioner:
phone_number_practitioner: 918273645
mobile_number_practitioner:
email_practitioner: test#test.pl
practitioner_specialty_id_update: 1
effective_date_specialty: 2019-01-01
expiry_date_specialty:
Edit blade
<div class="edit-practitioner" style="display: none;">
<form style="box-shadow: none;" action="/practitioner/update/{{$practitioner->practitioner_id}}" method="post"
class="j-pro" id="update-practitioner-form">
#csrf
<div class="j-content">
<div id="j-row-id" class="j-row">
<div class="row">
<div class="col-sm-12 col-lg-12 col-xl-5">
<div class=" j-unit">
<div class="j-divider-text j-gap-top-20 j-gap-bottom-45">
<span>Practitioner Information</span>
</div>
<label class="j-label">{{trans('personalData.effectiveDate')}}</label>
<div class="j-input">
<input type="date" value="{{$practitioner->effective_date}}"
name="effective_date_practitioner">
</div>
<label class="j-label">{{trans('personalData.expiryDate')}}</label>
<div class="j-input">
<input type="date" value="{{$practitioner->expiry_date}}"
name="expiry_date_practitioner">
</div>
<label class="j-label">{{trans('personalData.phoneNumber')}}</label>
<div class="j-input">
</label>
<input type="tel" value="{{$practitioner->phone}}"
name="phone_number_practitioner">
</div>
<label class="j-label">{{trans('personalData.mobileNumber')}}</label>
<div class="j-input">
<input type="tel" value="{{$practitioner->mobile}}"
name="mobile_number_practitioner">
</div>
<label class="j-label">{{trans('personalData.email')}}</label>
<div class="j-input">
<input type="email" value="{{$practitioner->email}}"
name="email_practitioner">
</div>
</div>
</div>
<div class="col-xl-1 j-unit"></div>
<div class="col-sm-12 col-lg-12 col-xl-6">
<div class="j-divider-text j-gap-top-20 j-gap-bottom-45">
<span>{{trans('settings.specialty')}}</span>
</div>
<select name="practitioner_specialty_id_update"
id="practitioner_specialty_id_update"
class="form-control-practitioner required">
#foreach($specialties as $specialty)
<option
value="{{$specialty->specialty_id}}">{{$specialty->name}}</option>
#endforeach
</select>
<label class="j-label">{{trans('personalData.effectiveDate')}}</label>
<div class="j-input">
<input type="date" value="{{$practitioner_specialty->effective_date}}"
name="effective_date_specialty">
</div>
<label class="j-label">{{trans('personalData.expiryDate')}}</label>
<div class="j-input">
<input type="date" value="{{$practitioner_specialty->expiry_date}}"
name="expiry_date_specialty">
</div>
</div>
</div>
</div>
<div class="j-divider j-gap-bottom-45 j-gap-top-10"></div>
<button type="submit"
class="btn btn-editpanel btn-success btn-round">Save changes
</button>
<!-- end /.footer -->
<button id="update-cancel-button-practitioner" type="button"
class="btn btn-editpanel btn-danger btn-round">Cancel
</button>
</div>
</form>
</div>
web.php
Route::post('/practitioner/update/{id}', 'Crud\Settings\PractitionerController#updatePractitioner')->name('updatePractitioner');
Controller:
<?php
namespace App\Http\Controllers\CRUD\Settings;
use App\Models\Practitioner;
use App\Models\PractitionerCompetenceLevel;
use App\Models\PractitionerSpecialty;
use App\Repositories\PractitionerRepository;
use Illuminate\Http\Request;
class PractitionerController extends CrudController
{
protected $repository;
public function __construct(PractitionerRepository $repository)
{
$this->middleware('auth');
$this->repository = $repository;
}
public function updatePractitioner($id, Request $request)
{
$this->validate($request, [
'effective_date_practitioner' => 'required',
'effective_date_specialty' => 'required',
]
);
$input = $request->all();
$input['data'][$this->repository->getIdName()] = $id;
$this->repository->update($input['data']);
return back()->with('successUpdate', 'Practitioner has been updated!');
}
}
My guess is that the data I want to update belongs to two different tables in DB one called practitioner and the other one called practitioner_specialty
As per your code you are trying to do mass assignment to your model
You may do this using the $fillable property on the model
protected $fillable = ['effective_date_practitioner','effective_date_specialty',......];
And you can use attach() method to updated data in related tables
I would like to read the contents of the intermediate table between the trainers and courses table to be able to flag the chackboxes of the active courses for a given trainer, how can I do?
Here you can look the trainers table
http://prntscr.com/nhcrl4
Here you can look the courses table
http://prntscr.com/nhcrvp
Here you can look the course_trainer (intermediate) table
http://prntscr.com/nhcsek
I thought of using the ternary, you advise me?
thanks a lot
this is the form
<div class="container">
<div class="row">
<div class="col-lg-12">
<form class="form-group" action="{{route('trainers.update', $trainer->id)}}" method="post" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="form-group">
<label for="name">Nome</label>
<input type="text" class="form-control" name="name" value="{{$trainer->name}}">
</div>
<div class="form-group">
<label for="surname">Cognome</label>
<input type="text" class="form-control" name="surname" value="{{$trainer->surname}}">
</div>
<div class="form-group">
<label for="description">Descrizione</label>
<textarea class="form-control" name="description" rows="8" cols="80">{!! $trainer->description !!}</textarea>
</div>
#foreach ($courses as $course)
<div class="form-check form-check-inline mb-2">
<input name="course_id[]" class="form-check-input" type="checkbox" value="{{$course->id}}">
<label class="form-check-label" for="course_id">{{$course->name_course}}</label>
</div>
#endforeach
<div class="form-group">
<img src="{{asset('storage/'.$trainer->image)}}" alt="">
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" name="image">
<label class="custom-file-label" for="image">Scegli un'immagine</label>
<div class="invalid-feedback"><strong>N.B.</strong> dimensione consigliata 160px x 160px</div>
</div>
<div class="form-group">
<input type="submit" class="form-control" value="MODIFICA ISTRUTTORE">
</div>
</form>
</div>
</div>
</div>
this is the edit function in controller
public function edit($id)
{
$trainer = Trainer::find($id);
$courses = Course::all();
return view('trainers.edit', compact('trainer','courses'));
}
this is the update function in controller
public function update(Request $request, Trainer $trainer)
{
$data = $request->all();
$trainer->update($data);
$trainer->courses()->sync($data['course_id']);
return redirect()->route('trainers.admin');
}
This is Trainer Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Trainer extends Model
{
protected $fillable = ['name','surname','description','image'];
public function courses(){
return $this->belongsToMany(Course::class)->withTimestamps();
}
}
This is Course Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
protected $fillable = ['name_course','description_course','logo_course'];
public function trainers(){
return $this->belongsToMany(Trainer::class)->withTimestamps();
}
}
This is Trainer Model
public function courses(){
return $this->belongsToMany('App\Course', 'course_trainer ', 'trainer_id', 'course_id')->withTimestamps();
}
This is Course Model
public function trainers(){
return $this->belongsToMany('App\Trainer', 'course_trainer ', 'course_id', 'trainer_id')->withTimestamps();
}
belongsToMany() method 4 parameters, the first one is the location of your model to link, the second is the name of the pivot table, the third one is the current model foreign key and the fourth one is the other's model foreign key.
now you can do something like this in the form
<input name="course_id[]" class="form-check-input" type="checkbox" #if($course->pivot->trainer_id == $trainer->id) "checked='' " #endif value="{{$course->id}}">
I solved the problem without changing the model ... it was enough to do this
#foreach ($courses as $course)
<div class="form-check form-check-inline mb-2">
<input name="course_id[]" class="form-check-input" type="checkbox" value="{{$course->id}}" #foreach ($trainer->courses as $value)
{{($course->id == $value->pivot->course_id) ? 'checked' : ''}}
#endforeach>
<label class="form-check-label" for="course_id">{{$course->name_course}}</label>
</div>
#endforeach