I have this error when I try to add data. I have 2 tables on my database, the (players) table and the (stats) table which are connected with the "player_id" being the foreign key to the players table.
players table:enter image description here
stats table:enter image description here
StatsController:
public function index(){
$stats = Stats::all();
return view('stats', ['stats' => $stats]);
}
public function addstats(){
if($this->request->method() == 'POST'){
$alert = request() -> validate([
'points' => 'required|numeric',
'average_points' => 'required|numeric',
'games' => 'required|numeric',
'duration' => 'required|numeric'
]);
$stats = new Stats;
$stats->player_id = $this->request->id;
$stats->points = $this->request->get('points');
$stats->average_points = $this->request->get('average_points');
$stats->games = $this->request->get('games');
$stats->duration = $this->request->get('duration');
if($stats -> save()){
echo 'Success';
}
}
return view('addstats', ['player_id' => $this->request->player_id]);
}
public function editstats(Stats $stats){
if($this->request->method() == 'POST'){
$alert = request() -> validate([
'points' => 'required|numeric',
'average_points' => 'required|numeric',
'games' => 'required|numeric',
'duration' => 'required|numeric'
]);
$stats->player_id = $this->request->id;
$stats->fullname = $this->request->get('points');
$stats->age = $this->request->get('average_points');
$stats->height = $this->request->get('games');
$stats->weight = $this->request->get('duration');
if($stats -> save()){
return redirect('stats/');
}
}
return view('editstats', ['stats' => $stats]);
}
public function destroy(Stats $stats){
$stats->delete();
return redirect('stats/');
}
addstats blade php:
#section('content')
<div class="container">
<form action="{{route('addstats')}}" method="POST">
#csrf
<input type="hidden" name="id" value="{{$player_id}}">
<p>Overall Points:</p>
<input type="number" name="points" class="form-control" value="{{Request::old('points')}}" required>
<p style="color: red">#error('points') {{$message}} #enderror</p>
<p>Average points per game:</p>
<input type="number" name="average_points" class="form-control" value="{{Request::old('average_points')}}" required>
<p style="color: red">#error('average_points') {{$message}} #enderror</p>
<p>Games:</p>
<input type="number" name="games" class="form-control" value="{{Request::old('games')}}" required>
<p style="color: red">#error('games') {{$message}} #enderror</p>
<p>Duration:</p>
<input type="number" name="duration" class="form-control" value="{{Request::old('duration')}}" required>
<p style="color: red">#error('duration') {{$message}} #enderror</p>
<button class="btn btn-primary">Submit</button>
</form>
</div>
#endsection
my Routes:
Route::middleware('auth')->group(function(){
Route::get('/', [PlayersController::class, 'index']);
Route::post('/addplayer', [PlayersController::class, 'addplayer'])->name('addplayer');
Route::get('/addplayer', [PlayersController::class, 'addplayer'])->name('addplayer');
Route::get('/editplayer/{players}', [PlayersController::class, 'editplayer'])->name('editplayer');
Route::post('/editplayer/{players}', [PlayersController::class, 'editplayer'])->name('editplayer');
Route::get('/destroy/{players}', [PlayersController::class, 'destroy'])->name('destroy');
Route::get('/stats/{player_id?}', [StatsController::class, 'index']);
Route::post('/addstats', [StatsController::class, 'addstats'])->name('addstats');
Route::get('/addstats', [StatsController::class, 'addstats'])->name('addstats');
Route::get('/editstats/{stats?}', [StatsController::class, 'editstats'])->name('editstats');
Route::post('/editstats/{stats?}', [StatsController::class, 'editstats'])->name('editstats');
Route::get('/destroy/{stats?}', [StatsController::class, 'destroy'])->name('destroy');
});
class Stats extends Model
{
use HasFactory;
protected $table = 'stats';
protected $fillable = [
'player_id','points','average_points','games','duration'
];
}
Related
I'm using a multipart form to send texts and image to database,
The data have been successfully sent to the database, but why in the console it is showing the data infull html ? not only the data that has been retrieved ?
this is my code
<template>
<div class="gabungPage">
<div class="row">
<div class="backgroundGabung" id="hrefGabung">
<div class="tulisanGabung p-5">
<div class="cardGabung">
<p class="teksGabung">Tingkatkan bisnismu sekarang dengan bergabung menjadi mitra JAI'</p>
<form #submit.prevent="submitForm">
<div class="form-group">
<label for="nama">Nama</label>
<input
type="text"
id="nama"
v-model="formulirs.nama"
class="form-control"
/>
</div>
<div class="form-group">
<label for="alamat">Alamat</label>
<input
type="text"
id="alamat"
v-model="formulirs.alamat"
class="form-control"
/>
</div>
<div class="form-group">
<label for="email">Email</label>
<input
type="text"
id="email"
v-model="formulirs.email"
class="form-control"
/>
</div>
<div class="form-group">
<label for="nomor">nomor</label>
<input
type="text"
id="nomor"
v-model="formulirs.nomor"
class="form-control"
/>
</div>
<div class="form-group">
<label for="image">Image</label>
<input
type="file"
id="image"
ref="imageInput"
#change="uploadImage"
/>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
<div class="tesss">
<h1> <span class="tulisKiri1">Gabung jadi</span> <br> <span class="tulisKiri2">mitra jahit</span></h1>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
formulirs: {
nama: '',
alamat: '',
nomor: '',
email: '',
image: null,
},
};
},
methods: {
uploadImage() {
this.formulirs.image = this.$refs.imageInput.files[0];
},
async submitForm() {
const formData = new FormData();
formData.append('nama', this.formulirs.nama);
formData.append('alamat', this.formulirs.alamat);
formData.append('email', this.formulirs.email);
formData.append('nomor', this.formulirs.nomor);
formData.append('image', this.formulirs.image);
axios.post('/api/submit-form', formData).then(
response => {
console.log(response);
this.$toast.success(`Data berhasil dikirim`,{
position: "bottom",
});
}
). catch(error => {
console.log('error');
this.$toast.error(`Terjadi kegagalan`,{
position: "bottom",
});
})
},
},
};
</script>
the routes/web.php
Route::post('/api/submit-form', [FormulirsController::class, 'store']);
the controller
public function store(Request $request)
{
$validatedData = $request->validate([
'nama' => 'required',
'alamat' => 'required',
'nomor' => 'required',
'email' => 'required|email',
'image' => 'required|image',
]);
$formulir = new Formulirs;
$formulir->nama = $validatedData['nama'];
$formulir->alamat = $validatedData['alamat'];
$formulir->nomor = $validatedData['nomor'];
$formulir->email = $validatedData['email'];
$image = $request->file('image');
$imageName = time().$image->getClientOriginalName();
$image->storeAs('public/images', $imageName);
$formulir->image = $imageName;
$formulir->save();
return back()->with('success', 'Data berhasil dikirim');
}
I have tried to show the data only by changing to
console.log(response.data)
But it got worse, it only shows full html page in the console, what should I do so that it doesn't display the full html page?
You're making an axios request and returning back method. This is used for redirecting in a monolitic app. I recommend you return a JSON response in your controller. Something like this:
public function store(Request $request)
{
$validatedData = $request->validate([
'nama' => 'required',
'alamat' => 'required',
'nomor' => 'required',
'email' => 'required|email',
'image' => 'required|image',
]);
$formulir = new Formulirs;
$formulir->nama = $validatedData['nama'];
$formulir->alamat = $validatedData['alamat'];
$formulir->nomor = $validatedData['nomor'];
$formulir->email = $validatedData['email'];
$image = $request->file('image');
$imageName = time().$image->getClientOriginalName();
$image->storeAs('public/images', $imageName);
$formulir->image = $imageName;
$formulir->save();
return back()->with('success', 'Data berhasil dikirim'); // this is yours
return response()->json('Data berhasil dikirim'); // 200 status code is the second param by default. You can change for whatever you want.
}
I'm following this article on how to add Recaptcha v2 to a Laravel and Vue js project.
https://www.itechempires.com/2018/05/how-to-implement-google-recapcha-with-vuejs-and-laravel-5-6/
I'm trying to implement it in my project but I'm getting this error on the page:
The recaptcha verification failed. Try again.
And in the network tab this error:
{recaptcha: ["The recaptcha verification failed. Try again."]}
And in the console:
POST http://highrjobsadminlte.test/submit 422 (Unprocessable Entity)
I'm trying to implement this on a Contact Form on my Contact.vue page.
Contact.vue:
<form #submit.prevent="submit">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name" v-model="fields.name" />
<div v-if="errors && errors.name" class="text-danger" style="font-size: 13px;">{{ errors.name[0] }}</div>
</div>
<div class="form-group">
<label for="email">E-mail</label>
<input type="email" class="form-control" name="email" id="email" v-model="fields.email" />
<div v-if="errors && errors.email" class="text-danger" style="font-size: 13px;">{{ errors.email[0] }}</div>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message" name="message" rows="5" v-model="fields.message"></textarea>
<div v-if="errors && errors.message" class="text-danger" style="font-size: 13px;">{{ errors.message[0] }}</div>
</div>
<div class="form-group">
<vue-recaptcha
v-model="fields.recaptcha"
ref="recaptcha"
#verify="onVerify"
sitekey="6LcAHcoZAAAAAFDOejn9e2LrogSpF41RMlXtrpDa">
</vue-recaptcha>
</div>
<div v-if="errors && errors.recaptcha" class="text-danger" style="font-size: 13px;">{{ errors.recaptcha[0] }}</div>
<button type="submit" class="btn btn-primary mt-3">Send message</button>
</form>
export default {
name: "Contact",
data() {
return {
fields: {},
errors: {},
}
},
methods: {
onVerify(response) {
this.fields.recaptcha = response;
},
submit() {
this.errors = {};
axios.post('/submit', this.fields, {
headers:{
'Content-Type':'application/json',
'Accept':'application/json'
}
}).then(({data: {fields}}) => {
this.$toast.success('Message sent successfully!');
this.$refs.recaptcha.reset();
}).catch(error => {
if (error) {
this.errors = error.response.data.errors || {};
}
});
},
},
}
Recaptcha.php (This is a rule):
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Zttp\Zttp;
class Recaptcha implements Rule
{
const URL = 'https://www.google.com/recaptcha/api/siteverify';
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
return Zttp::asFormParams()->post(static::URL, [
'secret' => config('services.recaptcha.secret'),
'response' => $value,
'remoteip' => request()->ip()
])->json()['success'];
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The recaptcha verification failed. Try again.';
}
/**
* Determine if Recaptcha's keys are set to test mode.
*
* #return bool
*/
public static function isInTestMode()
{
return Zttp::asFormParams()->post(static::URL, [
'secret' => config('services.recaptcha.secret'),
'response' => 'test',
'remoteip' => request()->ip()
])->json()['success'];
}
}
ContactFormController.php:
<?php
namespace App\Http\Controllers;
use App\Mail\ContactEmail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Rules\Recaptcha;
class ContactFormController extends Controller
{
public function submit(Request $request, Recaptcha $recaptcha) {
$this->validate($request, [
'name' => 'required|string',
'email' => 'required|email',
'message' => 'required',
'recaptcha' => ['required', $recaptcha],
]);
$contact = [];
$contact['name'] = $request->get('name');
$contact['email'] = $request->get('email');
$contact['subject'] = $request->get('subject');
$contact['message'] = $request->get('message');
// Mail Delivery logic goes here
Mail::to(config('mail.from.address'))->send(new ContactEmail($contact));
return response(['contact' => $contact], 200);
}
}
web.php:
Route::post('/submit', 'ContactFormController#submit');
And I have set recaptcha key and secret in config/services.php to point to my .env variables which are set in my .env file.
I want to return to the page with Link : localhost:8000/order/show/O1/T1.
O1 is $order->id_order and T1 is $trip->id_trip.
Here's my code.
Route::get('/order/show/{id_order}/{id_trip}', 'OrderController#show');
Route::get('/order/update_driver/{id_order}/{id_trip}', 'OrderController#update_driver');
Order Controller
public function show($id_order, $id_trip){
$trip = Trip::find($id_trip);
$order = Order::where(['id_order' => $id_order, 'id_trip' => $id_trip])->first();
$detail_order = Detail_Order::where(['id_order' => $id_order, 'id_trip' => $id_trip])->first();
$detail = Order::join('detail_order', 'order.id_order', '=', 'detail_order.id_order')
->where('order.id_order', $id_order)
->select('order.id_trip as order_trip',
'order.id_order as order_id',
'order.id_users as order_users',
'order.date_order as order_date',
'detail_order.id_seat as detail_seat',
'detail_order.users as detail_users')
->get();
$driver = Driver::all();
return view('travel.order.show', ['trip' => $trip, 'order' => $order, 'detail' => $detail, 'detail_order' => $detail_order, 'driver' => $driver]);
}
public function update_driver($id_order, $id_trip){
$driver = Input::get('id_users_driver');
Detail_Order::where('id_order', $id_order)
->update(['id_users_driver' => $driver]);
session()->flash('flash_success', 'Data has been updated');
return redirect('/order/show/{id_order}/{id_trip}');
}
View
<form method="get" action="/order/update_driver/{{ $order->id_order}}/{{ $order->id_trip}}">
<label>Driver</label>
<select class="form-control" name="id_users_driver" id="id_users_driver">
<option value=""> Driver </option>
#foreach($driver as $d)
<option value="{{$d->id_users}}"{{$detail_order->id_users_driver == $d->id_users ? 'selected' : ''}}>{{$d->name}}</option>
#endforeach
</select>
#if($errors->has('id_users_driver'))
<div class="text-danger">
{{ $errors->first('id_users_driver')}}
</div>
#endif
<input type="submit" class="btn btn-primary" value="Save">
</form>
It returned error Trying to get property 'id_order' of non-object.
Do you know how to make it return to localhost:8000/order/show/O1/T1? Thank you
I want to upload an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image.
Call to a member function getClientOriginalName() on null
Controller
public function store(Request $request)
{
$admin = $request->all();
$fileName = $request->file('foto')->getClientOriginalName();
$destinationPath = 'images/';
$proses = $request->file('foto')->move($destinationPath, $fileName);
if($request->hasFile('foto'))
{
$obj = array (
'foto' => $fileName,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
}
return redirect()->route('admin-index');
}
View
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
Error
You can check wheather you are getting file or not by var_dump($request->file('foto')->getClientOriginalName());
And make sure your form has enctype="multipart/form-data" set
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
Error because of client Side
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
you ned to add enctype="multipart/form-data" inside the form
If You are using the form builder version
{!! Form::open(['url' => ['store'],'autocomplete' => 'off','files' => 'true','enctype'=>'multipart/form-data' ]) !!}
{!! Form::close() !!}
Then In your Controller You can check if the request has the file
I have Created the simple handy function to upload the file
Open Your Controller And Paste the code below
private function uploadFile($fileName = '', $destinationPath = '')
{
$fileOriginalName = $fileName->getClientOriginalName();
$timeStringFile = md5(time() . mt_rand(1, 10)) . $fileOriginalName;
$fileName->move($destinationPath, $timeStringFile);
return $timeStringFile;
}
And the store method
Eloquent way
public function store(Request $request)
{
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile= $this->uploadFile($request->foto,$destinationPath );
}
Admin::create(array_merge($request->all() , ['foto' => $fotoFile]));
return redirect()->route('admin-index')->with('success','Admin Created Successfully');
}
DB Facade Version
if You are using DB use use Illuminate\Support\Facades\DB; in top of your Controller
public function store(Request $request)
{
$admin = $request->all();
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile = $this->uploadFile($request->foto,$destinationPath );
}
$obj = array (
'foto' => $fotoFile,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
return redirect()->route('admin-index');
}
Hope it is clear
After redirection,I try to retrieve session in home() using 'dd(session('key'))' but session auto cleared and got null value In laravel 5.4 and also i didn't found any error or warning message.
Before redirection session set and get are working.
I have below code:
LoginController.php
<?php
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\employers;
use App\Model\admin;
use Session;
use DB;
use Validator;
class LoginController extends Controller
{
public function index(){
$users = employers::all();
return view('user_view',['users'=>$users]);
}
public function insert_record(){
$users = new employers;
$users->userFname = 'Nikunj';
$users->userLname = 'Makwana';
$users->gender = 'Male';
$users->created_at = time();
$users->updated_at = time();
$users->save();
}
public function login(){
return view('admin/login',['errors'=>array()]);
}
public function home(){
dd(session('key'));
}
public function checklogin(Request $request){
$validator = Validator::make($request->all(), [
'username' => 'required|email',
'password' => 'required',
]);
if($validator->fails()) {
$errors = $validator->errors();
$validation_errors['username'] = $errors->first('username');
$validation_errors['password'] = $errors->first('password');
return view('admin/login',['errors'=>$validation_errors]);
}
$input = $request->all();
$username = $input['username'];
$password = $input['password'];
$admin_login = admin::where('username', $username)
->where('password', $password)
->count();
if($admin_login){
session(['key' => 'value']);
return redirect('admin_home');
}
else
{
return redirect('admin');
}
}
}
Views/admin/login.blade.php
<form method="post" action="{{ 'admin_login' }}">
{{ csrf_field() }}
<fieldset>
<label>
<span class="block input-icon input-icon-right">
<input type="text" name="username" class="span12" placeholder="Username" />
<i class="icon-user"></i>
</span>
</label>
<label>
<span class="block input-icon input-icon-right">
<input type="password" name="password" class="span12" placeholder="Password" />
<i class="icon-lock"></i>
</span>
</label>
<div class="space"></div>
<div class="clearfix">
<label class="inline">
<input type="checkbox" />
<span class="lbl"> Remember Me</span>
</label>
<button type="submit" class="width-35 pull-right btn btn-small btn-primary">
<i class="icon-key"></i>
Login
</button>
</div>
<div class="space-4"></div>
</fieldset>
</form>
Route/Web.php
<?php
Route::get('/', function () {
return view('welcome');
});
//For database Query
Route::get('/employers','UserController#index');
Route::get('/add_employer','UserController#add_employer');
Route::match(['get','post'],'/insert_employer /','UserController#insert_record');
// For Admin
Route::get('/admin','admin\LoginController#login');
Route::get('/admin_logout','admin\LoginController#logout');
Route::get('/admin_home','admin\LoginController#home');
Route::match(['get','post'],'/admin_login/','admin\LoginController#checklogin');
Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
protected $middleware = [
'\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class',
'\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class',
'\App\Http\Middleware\TrimStrings::class',
'\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class',
];
protected $middlewareGroups = [
'web' => [
'\App\Http\Middleware\EncryptCookies::class',
'\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class',
'\Illuminate\Session\Middleware\StartSession::class',
'\Illuminate\Session\Middleware\AuthenticateSession::class',
'\Illuminate\View\Middleware\ShareErrorsFromSession::class',
//'\App\Http\Middleware\VerifyCsrfToken::class',
'\Illuminate\Routing\Middleware\SubstituteBindings::class',
],
'api' => [
'throttle:60,1',
'bindings',
],
];
protected $routeMiddleware = [
'auth' => '\Illuminate\Auth\Middleware\Authenticate::class',
'auth.basic' => '\Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class',
'bindings' => '\Illuminate\Routing\Middleware\SubstituteBindings::class',
'can' => '\Illuminate\Auth\Middleware\Authorize::class',
'guest' => '\App\Http\Middleware\RedirectIfAuthenticated::class',
'throttle' => '\Illuminate\Routing\Middleware\ThrottleRequests::class',
'Role' => '\App\Http\Middleware\RoleMiddleware::class',
//'csrf' => 'App\Http\Middleware\VerifyCsrfToken'// add it as a middleware route
];
}