How to upload image file in Laravel? - html

I have a form which contains several fields including the upload file button that I want to use as an image uploader, (<input type="file" name="image" id="image" class='image'>). Other fields works fine and uploads everything on the database, however, in the image field, the filename of the file I uploaded is giving me this file name:
C:\laragon\tmp\php859A.tmp
... What should I do? Thank you: ) Here are the codes:
this is the form:
<html>
<div class="col-md-offset-4 col-md-4">
<form action="{{ $action }}" method="POST" enctype="multipart/form-data">
<h1> {{ $header }} </h1>
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name" value="{{ $name }}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Description</label>
<input type="text" class="form-control" id="description" name="description" placeholder="Description" value="{{ $description }}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Price</label>
<input type="number" class="form-control" id="product_price" name="product_price" placeholder="Price" value="{{ $product_price }}">
</div>
<div class="form-group">
<label for="image">SELECT IMAGE TO UPLOAD</label><br>
<input type="file" name="image" id="image" class='image'>
</div>
<div class="col-md-offset-2">
{!! csrf_field() !!}
<button type="submit" class="btn btn-default col-md-5" style="background:#0099ff; color:#f2f2f2;">{{ $button }}</button>
<button type="submit" class="btn btn-default col-md-5" style="background:#f4f4f4; color:#000;">Cancel</button>
</div>
</form>
</div>
</html>
These are my functions Create and Store in the controller:
public function create()
{
$data['action'] = route('beverage_store');
$data['button'] = 'Add';
$data['header'] = 'ADD BEVERAGE';
$data['name'] = old('name');
$data['description'] = old('description');
$data['product_price'] = old('product_price');
$data['image'] = old('image');
return view('layouts.beverages.beverageform',$data);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = $request->all();
#dd($input);
BeveragesModel::create($input);
return redirect()->route('beverages');
}
:)

Assuming you store the filename only on your database table, then you have to upload image somewhere else. So you could create something like:
private function upload($request)
{
$image_name = '';
if($request->hasFile('image'))
{
$image = $request->file('image');
$image_name = md5(uniqid()) . '.' . $image->getClientOriginalExtension();
$image->move(public_path() . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'beverages' . DIRECTORY_SEPARATOR, $image_name);
}
return $image_name;
}
public function store(Request $request)
{
$image_name = $this->upload($request);
$input = $request->all();
$beverage = BeveragesModel::create($input);
$beverage->image = $image_name;
$beverage->save();
return redirect()->route('beverages');
}

Related

how to make wordpress plugin form text field take numbers

I have a form in a plugin I am creatingin wordpress. The form is a simple test form and it has a hidden field and two text fields. If I enter a number into the text fields, it doesn't process it when I hit submit, it takes to me a page that says
It looks like nothing was found at this location. Maybe try a search?
here is the entire plugin showing the form and the action that processes the form.
<?php
/*
plugin name: deano plugin
description: deano test database to insert data into books table
author: Dean-O
*/
$path = preg_replace('/wp-content.*$/', '', __DIR__);
require_once($path.'/wp-load.php');
function deanoinsertdata() {
/**
* Dean-O database insert book function
*/
global $wpdb;
if(isset($_POST['submitbtn'])){
error_log('I am here');
$data=array(
'wp_id'=>$_POST['wp_id'],
'title'=>$_POST['title'],
'author'=>$_POST['author'],
);
$table_name = 'books';
$foundOne = 1;
error_log('table_name = '.$table_name);
error_log('foundOne = '.$foundOne);
/*$wp_idin = $_POST['wp_id'];
$titlein = $_POST['title'];
$authorin = $_POST['author'];
*/
$wp_idin = $data['wp_id'];
$titlein = $data['title'];
$authorin = $data['author'];
error_log('wp_idin = '.$wp_idin);
error_log('titlein = '.$titlein);
error_log('author = '.$authorin);
/*
see if the record is already in the table
*/
$sql = "select * from books";
print $sql;
$results = $wpdb->get_results($sql);
foreach($results as $result) {
if($result->wp_id==$wp_idin && $result->title==$titlein && $result->author==$authorin)
{
$foundOne = 0;
error_log('foundOne = 0');
}
}
//error_log('logged message');
if($foundOne==1) {
error_log('foundOne = 1 before insert');
$resultinsert = $wpdb->insert($table_name,$data);//, $format=NULL);
error_log('insert executed');
error_log('resultinsert = '.$resultinsert);
//wp_redirect( "http://localhost/tadpolewp/deano-plugin--duplicate-records/" );
//exit();
if($resultinsert==1) {
//header('Location: http://localhost/tadpolewp/deano-plugin-successful/');
error_log( 'successful' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-successful/" );
exit();
http://localhost/tadpolewp/deano-plugin-successful/
//error_log('Book saved 1');
//echo "Book Saved 1";
} else {
//header('Location: http://localhost/tadpolewp/deano-plugin-failed/');
error_log( 'failed to save' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-failed/" );
exit();
//error_log('unable to save');
//echo "Unable to Save";
}
} else {
//error_log('Duplicate record found');
//echo "Duplicate recortd found";
//header('Location: http://localhost/tadpolewp/deano-plugin-duplicate-records/');
error_log( 'duplicate record' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-duplicate-records/" );
exit();
}
}
?>
<form role="form" method="post">
<div class="form-group">
<?php
// get current user ID, with default value, if empty
$current_user_id = get_current_user_id();
?>
<input type="hidden" name="wp_id" value="<?php echo esc_attr( $current_user_id ); ?>" />
</div>
<div class="form-group">
<label>Field 1</label><br>
<input id="title" name="title" type="text" placeholder="<?php echo esc_attr( $current_user_id ); ?>" required="">
</div>
<div class="form-group">
<label>Field 2</label><br>
<input id="author" name="author" type="text" placeholder="Primary Author" required="">
</div>
<div class="row justify-content-center">
<div class="col-xs-4 col-sm-4 col-md-4">
<br><input type="submit" value="Submit1" class="btn btn-info btn-block" name="submitbtn">
</div>
</div>
</form>
<?php
}
add_shortcode('deanoputdatain','deanoinsertdata');
?>
The only way I can get the Field 1 or Field 2 to take numbers is to change them to type="number"
Is there a varchar type that I can use?
My database has the field set as a varchar.
Thanks in advance
Dean-O
You should be set action for your form.
For example: 'test.php' or '/'.
It worked well for me. I rewrite your code here:
<form role="form" method="post" action="{your menu slug}">
<div class="form-group">
<?php
// get current user ID, with default value, if empty
$current_user_id = get_current_user_id();
?>
<input type="hidden" name="wp_id" value="<?php echo esc_attr( $current_user_id ); ?>" />
</div>
<div class="form-group">
<label>Field 1</label><br>
<input id="title" name="title" type="text" placeholder="<?php echo esc_attr( $current_user_id ); ?>" required="">
</div>
<div class="form-group">
<label>Field 2</label><br>
<input id="author" name="author" type="text" placeholder="Primary Author" required="">
</div>
<div class="row justify-content-center">
<div class="col-xs-4 col-sm-4 col-md-4">
<br><input type="submit" value="Submit1" class="btn btn-info btn-block" name="submitbtn">
</div>
</div>
</form>

Laravel Displaying/returning data in json format instead of displaying/returning data in html format

i have weird situation in which data is displayed in json format instead of html !!
At route http://127.0.0.1:8000/addpost form to add post is displayed and the recently added post.
Its show the form to add post and when submit is clicked it returns data in json format insteaad of displaying the form and the post added.
1)why it is returning json data ?
2)how do i display data in html format ?
thats me route
web.php
Route::get('addpost','PostController#index');
Route::post('addpost','PostController#store');
Controller ->
PostController.php
class PostController extends Controller
{
public function index()
{
$posts = Post::latest()->first();
return view('addpost',compact('posts'));
}
public function store(Request $request)
{
$post =new Post();
$post->title= $request->input('title');
$post->body= $request->input('body');
if($request->hasfile('postimage'))
{
$file=$request->file('postimage');
$extention=$file->getClientOriginalExtension();
$filename=time().'.'.$extention;
$file->move('uploads/post',$filename);
$post->postimage=$filename;
}
else{
return $request;
$post->postimage='';
}
$post->save();
return back()->with('success', 'Your images has been successfully Upload');
}
}
and the view
<div class="container">
<div class="jumbotron">
#if(Auth::user())
<h3> Add new post with images</h3>
<form action="{{url('addpost')}}" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label>Title</label>
<input type="text" name="title" class="form-control" >
</div>
<div class="form-group">
<label>Body</label>
<input type="text" name="body" class="form-control" >
</div>
<div class="input-group">
<div class="custom-file">
<input type="file" name="image" class="custom-file-input">
<label class="custom-file-label">Choose file</label>
</div>
</div>
<button type="submit" name="submit" class="btn-brn-primary"> Save Post</button>
#if($posts)
#foreach($posts as $post)
<tr>
<td>{{$post->id}}</td>
<td>{{$post->title}}</td>
<td>{{$post->body}}</td>
<!-- <td><img src="{{asset('uploads/post/'.$post->image)}}" style="height: 150px;"></td>
<td>EDIT</td> -->
</tr>
#endforeach
#endif
#else
<h1>no</h1>
#endif
</form>
</div>
</div>
if($request->hasfile('postimage')) // -> you are checking for postimage, in your html
// markup the file filed is called "image",
// therefore you will never enter this if block
{
$file=$request->file('postimage');
$extention=$file->getClientOriginalExtension();
$filename=time().'.'.$extention;
$file->move('uploads/post',$filename);
$post->postimage=$filename;
}
else{
return $request; // here you are returning the $request object that
// causes your unformatted response
$post->postimage='';
}

edit and update text area in php

my php function is not working when im add my text area in form. other all input or working. if im add remark(text area) in form edit function cant show text in that remark. other input is visible but i cant save it again
please help me to fined my error
Code before "html"
<?php
function renderForm($id, $vehicle_type, $duration, $amount,$remarks, $error)
{
?>
my HTML form
<form action="" method="post">
<div class="row">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div class="col-lg-4 col-xs-6" class="form-group">
<label>Vehicle Type <span style="color:red;font-size:8px;"><i class="fa fa-asterisk" aria-hidden="true"></i></span></label>
<select name="vehicle_type" class="form-control">
<option <?php echo ($vehicle_type=='Bicycle')?'selected':'' ?>>Bicycle</option>
<option <?php echo ($vehicle_type=='Bike')?'selected':'' ?>>Bike </option>
<option <?php echo ($vehicle_type=='Cars')?'selected':'' ?>>Cars </option>
<option <?php echo ($vehicle_type=='Truck')?'selected':'' ?>>Truck</option>
<option <?php echo ($vehicle_type=='Others')?'selected':'' ?>>Others</option>
</select>
</div>
<div class="col-lg-4 col-xs-6" class="form-group">
<label>Duration </label> <span style="color:red; font-size:8px; "><i class="fa fa-asterisk" aria-hidden="true"></i></span>
<input type="text" value="<?php echo $duration; ?>" name="duration" class="form-control" maxlength="20" placeholder="Eg: 4 Hrs">
</div>
<div class="col-lg-4 col-xs-6" class="form-group">
<label><i class="fa fa-inr" aria-hidden="true"></i> Amount</label> <span style="color:red;font-size:8px;"><i class="fa fa-asterisk" aria-hidden="true"></i></span>
<input type="number" name="amount" value="<?php echo $amount; ?>" class="form-control" placeholder="00">
</div>
</div>
<div class="row">
<div class="col-lg-4 col-xs-6" class="form-group">
<label>Remarks</label>
<textarea class="form-control" name="remarks" <?php echo htmlspecialchars($remarks); ?> rows="3" placeholder="Enter ..."></textarea>
</div>
<div id="butn" class="col-lg-3 col-xs-3">
<button class="myButton" type="submit" name="submit" value="Submit" class="btn btn-block btn-success btn-lg">SAVE</button>
</div>
</div>
</form>
Code after "html"
<?php
}
// connect to the database
include('connection.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$vehicle_type = mysql_real_escape_string(htmlspecialchars($_POST['vehicle_type']));
$duration = mysql_real_escape_string(htmlspecialchars($_POST['duration']));
$amount = mysql_real_escape_string(htmlspecialchars($_POST['amount']));
$remarks = mysql_real_escape_string(htmlspecialchars($_POST['remarks']));
if ($vehicle_type=='' || $duration=='' || $amount=='' || $remarks=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $vehicle_type, $duration, $amount, $remarks, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE price_normal SET vehicle_type='$vehicle_type', duration='$duration', amount='$amount', remarks='$remarks', WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: pnormal.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM price_normal WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$vehicle_type = $row['vehicle_type'];
$duration = $row['duration'];
$amount = $row['amount'];
$remarks = $row['remarks'];
// show form
renderForm($id, $vehicle_type, $duration, $amount, $remarks,'');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
Take a look at the actual HTML in your browser. You're rendering the "remarks" content as an attribute of the textarea element:
<textarea class="form-control" name="remarks" <?php echo htmlspecialchars($remarks); ?> rows="3" placeholder="Enter ..."></textarea>
It should be the content of that element:
<textarea class="form-control" name="remarks" rows="3" placeholder="Enter ..."><?php echo htmlspecialchars($remarks); ?></textarea>

Laravel 5.4 not registrating users to database,

I'm simply trying to make my register form submit to my database, but my problem is you enter the info to the form press submit and it just reloads the page and does not send anything to the database.
originally it would submit what i entered but when you went to login it would just reload the page and not redirect, so i changed some stuff one thing lead to another now its not doing anything and i cannot pin-point the problems.
RegisterController.php
namespace App\Http\Controllers\Auth;
use App\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = ('index');
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest:admin');
}
routes/web.php
<?php
Auth::routes();
Route::get('/index', 'HomeController#index');
Route::prefix('/admin')->group(function() {
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminController#index')->name('admin.dashboard');
Route::get('/logout', 'Auth\AdminLoginController#logout')->name('admin.logout');
});
Route::prefix('/admin')->group(function() {
Route::get('register', 'Auth\AdminRegisterController#showRegistrationForm');
Route::post('register', 'Auth\AdminRegisterController#register')->name('admin.register');
});
Route::get('about', function () {
return view('about');
});
Route::get('advertise', function () {
return view('advertise');
});
Route::get('index', function () {
return view('index'); })->middleware('auth');
register.blade.php
#extends('header')
<div id="form-su" style="background-color: #d8b6ff" >
<h3 class="signuph"> Register </h3>
</div>
<form method="POST" action="{{ route('admin.register') }}">
<input type="hidden" name="_token" value="{!! csrf_token() !!}">
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
<div class="div-su {{ $errors->has('name') ? ' has-error' : '' }}">
<input class="signup-menu2{{ $errors->has('name') ? ' has-error' : '' }}" " type="text" name="name" value="{{ old('name') }}" placeholder=" Name.." required >
<input class="signup-menu2{{ $errors->has('email') ? ' has-error' : '' }}" " type="email" name="email" value="{{ old('email') }}" placeholder=" Email.." required >
</br>
<input class="signup-menu2{{ $errors->has('password') ? ' has-error' : '' }}" type="password" name="password" placeholder=" Password.." required >
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
</br>
<label> confirm password
<input class="signup-menu2 " type="password" name="password_confirmation" placeholder=" Confirm Password.." required >
</label>
#endif
</br>
<button class="signup-btn" type="submit" name="submit" value="submit"> Sign Up </button>
</form> </br>
<p class="forgotten-password" href=""> Forgotten password?</p> </br>
<p class="log-in-here" a href="">Log in here </p> </br>
</div>
</div>
</form>
</body>
</html>
also for some reason the confirm password input does not show on the form in the browser, but if you submit the form it pops up... whys that?
i know that you may need to see other pages so don't hesitate to ask for them
i appreciate any help guys,

trouble appending/combining two variables

Here's my code, It's a forum, there are posts with dislike buttons,like buttons, and a text box for commenting with each individual post, check the screenshot below. I'm trying to put the $comments variable, which are the comments itself, at the end of $posts so it displays below the posts properly like the like buttons and comment box are displayed.
I'm trying to just get the comments displayed underneath the comment box. If I call displayComments(the function in $comments definition) in the for each loop then the comments get displayed separately from the posts I've tried combining the $comments at the end of $posts with this operator +, and I've tried making a new variable equal to the both of them. Here's the code(not the full file).
<?php
include("connect.php");
include("check.php");
include("Trying.php");
include("Comment.php");
if(isset($_POST['username'])){
if (isset($_POST['post'])) {
if ($_FILES['postimg']['size'] == 0)
{
$postbody = $_POST['postbody'];
$loggedInUserId = check::isLoggedIn();
if (strlen($postbody) > 160 || strlen($postbody) < 1)
{
die('Incorrect length!');
}
connect::query('INSERT INTO dry_posts VALUES (null, :postbody, NOW(),\'\',0,0)', array(':postbody'=>$postbody));
}
}
if (isset($_POST['comment'])) {
$postid = $_GET['postid'];
$commentbody = $_POST['commentbody'];
if (strlen($commentbody) > 160 || strlen($commentbody) < 1) {
die('Incorrect length!');
}
connect::query('INSERT INTO comments VALUES (null,:comment, NOW(), :postid)',array(':comment'=>$commentbody,':postid'=>$postid));
//}
}
$dbposts = connect::query('SELECT * FROM dry_posts ORDER BY id DESC');
$posts = "";
$comments = Comment::displayComments($p['id']);
foreach($dbposts as $p){
if (!connect::query('SELECT post_id FROM dry_likes WHERE post_id=:postid', array(':postid'=>$p['id']))) {
$posts .="<img src='".$p['postimg']."'>".htmlspecialchars($p['body'])."
<form action='try.php?postid=".$p['id']."' method='post'>
<input type='submit' name='like' value='Like'>
<span>".$p['likes']." likes</span>
<input type='submit' name='dislike' value='Dislike'>
<span>".$p['dislikes']." dislikes</span>
</form>
<hr /></br />
;
<form action='try.php?postid=".$p['id']."' method='post'>
<textarea name='commentbody' rows='3' cols='50'></textarea>
<input type='submit' name='comment' value='Comment'>
</form>
<hr /></br />
";
//Comment::displayComments($p['id']);
}
else{
$posts .="<img src='".$p['postimg']."'>".htmlspecialchars($p['body'])."
<form action='try.php?postid=".$p['id']."' method='post'>
<input type='submit' name='like' value='Like'>
<span>".$p['likes']." likes</span>
<input type='submit' name='dislike' value='Dislike'>
<span>".$p['dislikes']." dislikes</span>
</form>
<hr /></br />
<form action='try.php?postid=".$p['id']."' method='post'>
<textarea name='commentbody' rows='3' cols='50'></textarea>
<input type='submit' name='comment' value='Comment'>
</form>
<hr /></br />
";
//Comment::displayComments($p['id']);
}
}
?>
<form action='try.php' class = "forum" method="post" enctype="multipart/form-data">
<textarea name="postbody" rows="4" cols="60" class = "text"></textarea>
<br />Upload an image:
<input type="file" name="postimg">
<input type="submit" name="post" value="Post">
</form>
<div class="posts">
<?php echo $posts;
?>
</div>
Here's the function I'm calling in the $comments variable
public static function displayComments($postid)
{
$comments = connect::query('SELECT * FROM comments WHERE post_id=:postid',array(':postid'=>$postid));
foreach($comments as $comment)
{
echo $comment['comment']."<hr />";
}
}
I know this won't help a lot of people but I'm just not sure what to do, How do you suggest I get everything to display inline, should rearrange my code?