How to save data into mysql database from laravel route post - php

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

Related

Laravel blade checkbox is always invalidated

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'
]);

Laravel Inserting Data to Database

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 :)

Laravel 5: Database doesn't save through dropdown

I want to save some data through dropdownlist .. after loading the page, database also fetched with the dropdown but it doesn't save after I clicked the save button. I think there is problem with Course migration table but I couldn't get it.
[Scenery is while taking courses student can take a class from the dropdown list.]
Here is my contoller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Course;
use App\TheClass;
use Redirect;
class courseController extends Controller
{
public function index()
{
$alldata=Course::all();
return view('course.index',compact('alldata'));
}
public function create()
{
$input=\App\TheClass::all();
return view('course.create',compact('input'));
}
public function store(Request $request)
{
$input = $request->all();
Course::create($input);
return redirect('course');
}
}
Here is my view page:
<html>
<head>
<title> Create 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> Create course </h3>
{!! Form::open(array('route' => 'course.store','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" placeholder="Code">
</div>
<div class="form-group">
<label>Course Title</label>
<input type="text" name="course_title" class="form-control" placeholder="Title">
</div>
<div class="form-group">
<label>Course Credit</label>
<input type="text" name="course_credit" class="form-control" placeholder="Credit">
</div>
<div class="form-group">
<label for="">Class</label>
<select class="form-control input-sm" name="class_id" >
#foreach($input as $row)
<option value="{{$row->class_id}}">{{$row->class_name}}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
{!! Form::close() !!}
</div>
</body>
</html>
Course Table Migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCourseTable extends Migration
{
public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->increments('course_id');
$table->string('course_code',10);
$table->string('course_title',50);
$table->string('course_credit');
$table->integer('class_id')->unsigned();
$table->timestamps();
$table->foreign('class_id')->references('id')->on('classes');
});
}
public function down()
{
Schema::drop('courses');
}
}
The Class table Migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateClassTable extends Migration
{
public function up()
{
Schema::create('classes', function (Blueprint $table) {
$table->increments('id');
$table->string('class_name',10);
$table->timestamps();
});
}
public function down()
{
//
}
}
Change {{$row->class_id}} to {{$row->id}}
Because your classes table does not have class_id column.
First of all you need to add $fillable to your model as create
method uses Mass Assignment.
Secondly I dont see any category field in migrations. Your select
has name category so in database also should be category field.
Basically here you need to use One To Many
P.S. Don't have enough points for comments so answered.

Database couldn't update through Laravel

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.

Laravel 5.1 Login Controller Doesnt Work Well

I'm new to laravel. I have a problem with my login control where I can't match the data from my form and the database.
The error message said :
DecryptException in BaseEncrypter.php line 45: The payload is invalid.
Controller
namespace App\Http\Controllers;
use DB;
use Hash;
use Crypt;
use Validator;
use Illuminate\Http\Request;
use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class LoginControl extends Controller
{
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required',
'password' => 'required',
]);
if ($validator->fails()) {
return redirect('/login')
->withErrors($validator)
->withInput();
}
else{
$email = $request->email;
$password = $request->password;
$results = DB::select('select * from users where email = ? and password = ?', [$email,$password]);
$pass = Crypt::decrypt($request->password);
if($results == NULL){
return redirect('/login');
}
else{
return redirect('/');
}
}
}
}
Router
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/register', function () {
return View::make('register');
});
Route::get('/login', function() {
return View::make('login');
});
Route::post('actionregis', 'RegisControl#store');
Route::post('actionlogin', 'LoginControl#login');
View
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<title>Laravel Quickstart - Basic</title>
<!-- CSS And JavaScript -->
</head>
<body>
<div class="container">
<nav class="navbar navbar-default">
<!-- Navbar Contents -->
</nav>
</div>
<div class="panel-body">
<div class="col-md-8 col-md-offset-2">
<!-- New Task Form -->
<form action="/testing/public/actionlogin" method="POST" class="form-horizontal">
{{ csrf_field() }}
#if (count($errors) > 0)
<!-- Form Error List -->
<div class="alert alert-danger">
<strong>Whoops! Something went wrong!</strong>
<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Task Name -->
{!! csrf_field() !!}
<div class="form-group">
<label for="user">Email</label>
<input type="text" name="email" id="task-email" class="form-control">
</div>
<div class="form-group">
<label for="user">Password</label>
<input type="password" name="password" id="task-password" class="form-control">
</div>
<div class="form-group">
<input type="checkbox" name="remember"> Remember Me
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Login</button>
</div>
</form>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
You are decrypting an unecrypted string (this is why you are getting the error):
$pass = Crypt::decrypt($request->password);
Why is this even here? $pass is not doing anything.
As of now, you are searching for a user with an unecrypted password.
To check if the password is valid, you do NOT decrypt the password in DB, you encrypt the inserted one and see if they match.
How are you encrypting the password when inserting it?
Laravel provides a mostly-done authentication by default, you should use it if you don't know what you are doing and want to have authentication as secure as possible. Read about it here: http://laravel.com/docs/5.0/authentication
To write your own authentication, you should use the Hash class:
$password = Hash::make('some_password'); // Use this to hash your password (you can store that in the DB)
// To check the password, you parse the user's hashed password from the DB
... // <- parse user here
$hashedPassword = $user->password;
// Password checking
if (Hash::check('some_password', $hashedPassword))
{
// The passwords match...
}
Since you have a lot of data maybe the column type in your database is too small and you are therefore getting this error.
Try to set the column to longtext instead of text in your migration and see if that works.

Categories