I am still new to Laravel, so I am trying to learn it from a certain website and try inserting data into database mysql by using form.
this is the view code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Form Tambah Data</h1>
<form action="/home/simpan" method="post">
{{ csrf_field() }}
Nama <input type="text" name="nama" required="required"><br/>
Umur <input type="number" name="umur" required="required"><br/>
Kota <input type="text" name="kota" required="required"><br/>
<input type="submit" value="Simpan Data">
</form>
</body>
</html>
and then this is the web.php code
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', 'HomeController#index');
Route::get('/profil', function (){
return view('profil');
});
Route::get('/home/tambah','HomeController#tambahData');
Route::post('/home/simpan','HomeController#simpan');
And this one is the controller codes
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class HomeController extends Controller
{
//
public function index(){
//mengambil data dari tabel siswa
$mahasiswa = DB::table('mahasiswa')->get();
//mengirim data ke view mahasiswa
return view('mahasiswa', ['mahasiswa' => $mahasiswa]);
}
public function tambahData(){
return view('form_data');
}
public function simpan(Request $request){
DB::table('mahasiswa')->insert([
'nama' => $request->nama,
'umur' => $request->umur,
'kota' => $request->kota
]);
return redirect('/home');
}
}
The table in database has 4 columns, "id_mahasiswa, nama, umur, kota" and I try to only insert the data to 3 columns. But then, it always shows this error.
"Field 'id_mahasiswa' doesn't have a default value"
Can anyone tell me the solution for this?
It appears possibly that your database column "id_mahasiswa" within your "mahasiswa" table has a NOT NULL constraint and no default value so when you are trying to insert your record without a value for "id_mahasiswa" your query fails.
If the above is true you need to either provide a value for the field or change the design of the table you are working with.
I reviewed you code. In your phpmyadmin change the "id_mahasiswa" column default value to null for example :)
Related
I'm using laravel 9. When I check a checkbox and save it, I always get the error The calculator field must be true or false.
Route::get('/', function () {
return view('welcome');
});
Route::post('save', function(Request $request) {
$request->validate([
'calculator' => 'required|boolean'
]);
return redirect('/');
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
#if($errors->any())
<div class='alert alert-danger rounded-0 mb-0'>
{!! implode('<hr />', $errors->all(':message')) !!}
</div>
#endif
<form method="post" action="save">
#csrf
<div>
<input type="checkbox" class="form-control" name="calculator" id="calculator" />
<label for="calculator">Calculator</label>
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>
That's because Laravel sends checkbox value as on
You can see that if you dump your request:
dd($request->input());
In order to bypass that, you can add a value to your checkbox:
<input type="checkbox" class="form-control" value="1" name="calculator" id="calculator" />
This way, Laravel will now send 1 as your input, and you will be able to validate it with boolean rule.
Also, you can use a different approach. Laravel provides accepted rule as well:
The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.
So in this case, you would just change your validation rule:
$request->validate([
'calculator' => 'required|accepted'
]);
I have the web.php file
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
Route::get('/', function () {
return view('welcome');
});
Route::post('/upload', function (Request $request) {
$name=$request->file("thing")->getClientOriginalName();
Storage::disk("google")->putFileAs("",$request->file("thing"),$name);
})->name("upload");
?>
and HTML code like
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Google drive integration in laravel</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12">
<br><br><br>
<form action="/upload" method="post" enctype="multipart/form-data">
#csrf
<input type="file" class="form-control" name="thing" id="title">
<p id="s"></p>
<br>
<input type="submit" class="btn btn-sm btn-block btn-danger" value="Upload">
</form>
</div>
</div>
</div>
</body>
</html>
I want the data that is received in $name variable in the Route::post to be saved in the database.
like if I have MySQL database name "registration" having table "books" and I want to save this value in column "URL"
How can I do this?
First move the file and after that save the records:
Route::post('/upload', function (Request $request, Table $table) {
$name=$request->file("thing")->getClientOriginalName();
$request->file->move('dirname', $name);
$table->column_name = "dirname/{$name}";
$table->save();
})->name("upload");
First for checking database table exist or not
Schema::connection('mysql')->hasTable('books')
this will return true if exist or else return false
for inserting into database
DB::table('books')->insert(['URL'=>$name])
Final code will be
$tableExist=Schema::connection('mysql')->hasTable('books');
if($tableExist){
DB::table('books')->insert(['URL'=>$name]);
}
Also you can use connection for query insert also
DB::connection('mysql')->table('users')->insert(['URL'=>$name]);
Also connection method not required if you are using default connection.
For imports
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
First you need to edit your .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=registration
DB_USERNAME=root
DB_PASSWORD=secretPassword
Inserting your data would work like that
First you need to import the Database class
use Illuminate\Support\Facades\DB;
Then execute the insert statement
DB::insert('insert into books (URL) values (?)', [$name]);
You probably have more then one column inside your table
DB::insert('insert into books (URL, AnotherColumn) values (?,?)', [$name,'anotherValue']);
Source laravel-docs
Hello this my project with laravel to send an email by using mailtrap
this is my sendemail controller
<?php
namespace App\Http\Controllers;
use App\Model\Sendemail;
use Illuminate\Http\Request;
use Mail;
use App\Mail\TestStarted;
class SendemailController extends Controller
{
public function start(Request $request)
{
$send_email = Mail::to($request->email)->send(new TestStarted);
if ($send_email)
{
return redirect()->back()->with('success', 'Sens email
successfully.');
}
}
}
and this function to share the approval student into studentcontroller
public function shareapproval($uniid)
{
$approval = Student :: where ('uniid', $uniid)->firstOrFail();
return view('SendEmail.Request.share',compact('approval'));
}
and this TestStarted.php in Mail file
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class TestStarted extends Mailable
{
use Queueable, SerializesModels;
public function build()
{
return $this->view('SendEmail.Request.mail');
return redirect()->back()->with('success', 'Sens email successfully.');
}
}
this is in config.mail.php
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'testgp2#system.com'),//
'name' => env('MAIL_FROM_NAME', 'Example'),
],
and this is my form to write the instructor email to send the email
#extends('layouts.app')
#section('content')
<div class="container">
<form method="post" action="/sendemail">
#csrf
<h1> send email </h1>
<br>
<<div class="form-group">
<label for="email">write the instructor email</label><br>
<input type="text" id="email" name="email" class="form-control" >
</div>
<button type="submit" class="btn btn-primary">send </button><br>
</form>
</div>
#endsection
and this is the content of mail I want to send it
this is mail.blade.php in (resources\views\SendEmail\Request\mail.blade.php)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-enguiv="X-UA-compatible" content="ie=edge">
<title>document </titel>
</head>
<body background-color: coral>
<h2> thank you for your order </h2>
</body
</html>
Finally, this is my route
Route::post('/student/share-approval/{uniid}',
'StudentController#shareapproval');
//SendEmail
Route::post('/sendemail','SendemailController#start');
Route::get('/start','SendemailController#start');
and I set up my .env with MAIL_USERNAME and MAIL_PASSWORD as shown in my account on mailtrap
Okay, let's start from the route. You're pointing the same method for the GET and POST request:
Route::post('/sendemail','SendemailController#start');
Route::get('/start','SendemailController#start');
As a result the mail field Mail::to($request->email) is getting null. Which could be a reason behind failure. So try to use different methods for handling GET and POST requests instead of one.
Route::get('/start','SendemailController#start');
Route::post('/sendemail','SendemailController#sendMail');
Secondly, in the code below, you are returning twice. But in real life it will only execute the first one and ignore the second one.
public function build()
{
// this is executing
return $this->view('SendEmail.Request.mail');
// this is getting ingorned
return redirect()->back()->with('success', 'Sens email successfully.');
}
I have a project that is going to have 8 different forms all updating the same 'user' table in my database. I have the user authentication working and it makes a user in the table on my localhost mysql database. However when I start updating the table I keep getting errors such as email is not unique or http errors or ReflectionException in RouteDependencyResolverTrait.php line 57: Internal error: Failed to retrieve the default value.
I have tried everything, my create works but it makes a new row and doesn't update the existing row which the user is signed in on.
I'm only new to Laravel 5.4 and finished going through all the Laracasts, so I'm absolutely stumped at what to do.
Does anyone have any thoughts or know how to fix it or restructure it better? Please let me know if I have missed anything out. I have been trying to get this working for 2 days.
Basics.php
<?php
namespace App;
class Basics extends Model
{
public $table = "users";
protected $fillable = [
'family_name',
'given_names'
];
}
BasicsController.php
class BasicsController extends Controller
{
public function index()
{
$user = \Auth::user();
return view('/details/basics', compact('user'));
}
public function update(Request $request, $id)
{
$basics = Basics::find($id);
$basics->family_name = $request->input('family_name');
$basics->given_names = $request->input('given_names');
$basics->save();
return redirect("/details/basics");
}
}
basics.blade.php
#extends ('layouts/app')
#section ('content')
{{--Do #includes for all form components with the components file--}}
#include ('layouts/header')
<main class="main">
<form action="/details/basics" method="POST">
<input type="hidden" name="_method" value="PATCH">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<fieldset>
<label>Family name</label>
<input type="text" name="family_name" placeholder="Family name" value="{{ old('family_name') }}" />
</fieldset>
<fieldset>
<label>Given names</label>
<input type="text" name="given_names" placeholder="Given names" value="{{ old('given_names') }}" />
</fieldset>
<button type="submit" value="Save" name="save" class="button button-primary button-wide">Save</button>
</form>
</main>
#endsection
web.php
Route::get('/', function () {
return view('welcome');
});
// Authentication Routes
Auth::routes();
Route::get('/logout', 'Auth\LogoutController#destroy');
Route::get('/home', 'DashboardController#index');
Route::get('/dashboard', function () {
$user = Auth::user();
return view('dashboard', compact('user'));
});
// Eligibility Assessments
Route::get('/assessment/student', 'AssessmentController#index');
Route::post('/assessment/results', 'AssessmentController#store');
// Details
Route::get('/details/basics', 'BasicsController#index');
Route::patch('/details/basics', 'BasicsController#update');
You need to add a rule in your post request which will exclude the email field when updating the model. This is why you're getting the email is not unique error. Although you're not posting the email field but still the save method is doing that. Try using post instead of patch. Just for debugging purposes in your Route.php
I want to Edit my Database through Laravel Form. Edit do works but when i want to update the database it's showing the following Error.
MethodNotAllowedHttpException in RouteCollection.php line 219:
here is my Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Course;
class courseController extends Controller
{
public function index()
{
$alldata=Course::all();
return view('course.index',compact('alldata'));
}
public function create()
{
return view('course.create');
}
public function store(Request $request)
{
$input = $request->all();
Course::create($input);
return redirect('course');
}
public function show($id)
{
//
}
public function edit($id)
{
$course=Course::findOrFail($id);
return view('course.edit',compact('course'));
}
public function update(Request $request, $id)
{
$input = $request->all();
$data=Course::findOrFail($id);
$data->update($input);
return redirect('course');
}
public function destroy($id)
{
$data=Course::findOrFail($id);
$data->delete($input);
return redirect('course');
}
}
Here is my Edit Page:
<html>
<head>
<title> Update Course </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" >
<h3> Update course </h3>
{!! Form::open(array('route' =>['course.update',$course->course_id],'class'=>'form-horizontal')) !!}
{!! Form::token(); !!}
<?php echo csrf_field(); ?>
<div class="form-group">
<label >Course Code</label>
<input type="text" name="course_code" class="form-control" value="{{$course->course_code}}">
</div>
<div class="form-group">
<label >Course Title</label>
<input type="text" name="course_title" class="form-control" value="{{$course->course_title}}">
</div>
<div class="form-group">
<label>Course Credit</label>
<input type="text" name="course_credit" class="form-control" value="{{$course->course_credit}}">
</div>
<button type="submit" class="btn btn-default">Update</button>
{!! Form::close() !!}
</div>
</body>
</html>
Here is the route:
<?php
Route::resource('course','courseController');
Route::group(['middleware' => ['web']], function () {
});
If anyone can solve the problem.please help.
When you try to edit you need to add method type according this link.
Specifying different methods
You can use methods other than POST with your forms. Pass the 'method'
you want in the array argument. Valid methods are 'get', 'put',
'patch', 'post', or 'delete'.
So in your case you need to add 'method' => 'patch' to your Form::open..
So your final code in blade will look like this:
{!! Form::open([
'method' => 'PATCH',
'route' => ['course.update',$course->course_id],
'class'=>'form-horizontal'
]) !!}
Extra
I can see you are using php tags like <?php echo csrf_field(); ?>, I assume you know in Laravel you can use {{ csrf_field() }} which is equal, but since I do not have in depth knowledge about your code, so it is left to you.