How to upload image to Laravel storage? - laravel

I'm trying to implement this guide on how to upload an image to the laravel storage but when I submit, it shows that the page is expired. There is not error report in the log which makes it difficult to debug.
web.php:
Route::get('/upload-image', [StorageController::class, 'index']);
Route::post('/save', [StorageController::class, 'save']);
StorageController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
use App\Models\Photo;
class StorageController extends Controller
{
public function index()
{
return view('image');
}
public function save(Request $request)
{
$validatedData = $request->validate([
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
]);
$name = $request->file('image')->getClientOriginalName();
$path = $request->file('image')->store('public');
$save = new Photo;
$save->name = $name;
$save->path = $path;
$save->save();
return redirect('upload-image')->with('status', 'Image Has been uploaded');
}
}
Model Photo.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
use HasFactory;
}
Laravel view to upload the image image.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>Laravel 8 Uploading Image</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
#if(session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
<div class="card">
<div class="card-header text-center font-weight-bold">
<h2>Laravel 8 Upload Image Tutorial</h2>
</div>
<div class="card-body">
<form method="POST" enctype="multipart/form-data" id="upload-image" action="{{ url('/save') }}" >
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="file" name="image" placeholder="Choose image" id="image">
#error('image')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
#enderror
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
So when I navigate to localhost/upload-image it shows the view and I can choose a file in the input form but as soon as I click on the submit button, the page navigates to /save and shows 419 | Page Expired with no log entry. The browser console shows:
POST http://127.0.0.1:8000/save 419 (unknown status)

You are not passing #csrf token in form request:
<form method="POST" enctype="multipart/form-data" id="upload-image" action="{{ url('/save') }}" >
#csrf
Please pass as per above code example then it will be work.

You should include #csrf in your form tags.
<form method="POST" enctype="multipart/form-data" id="upload-image" action="{{ url('/save') }}" >
#csrf
</form>

Related

ErrorException Array to string conversion

i am facing ErrorException Array to string conversion, I am new in laravel. please help me in detail if you can,please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can
This is my code
<?php
namespace App\Http\Controllers;
use Redirect,Response;
use Illuminate\Http\Request;
use App\Models\Test;
use File;
class JsonController extends Controller
{
public function index()
{
return view('json_form');
}
public function download(Request $request)
{
$data = $request->only('name','email','mobile_number');
$test['token'] = time();
$test['data'] = json_encode($data);
Test::insert($test);
$fileName = $test['token']. '_datafile.json';
File::put(public_path('/upload/json/'.$fileName),$test);
//return download(public_path('/upload/jsonfile/'.$fileName));
$headers = [ 'Content-Type' => 'application/json', ];
return response()->download($test, 'filename.json', $headers);
//return response()->download(public_path('file_path/from_public_dir.pdf'));
}
}
This is my jeson.blade.php
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Store Data To Json Format In Database - Tutsmake.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<style>
.error{ color:red; }
</style>
</head>
<body>
<div class="container">
<h2 style="margin-top: 10px;">Laravel Store Data To Json Format In Database - Tutsmake.com</h2>
<br>
<br>
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<br>
#endif
<form id="laravel_json" method="post" action="json-file-download">
#csrf
<div class="form-group">
<label for="formGroupExampleInput">Name</label>
<input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
</div>
<div class="form-group">
<label for="email">Email Id</label>
<input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
</div>
<div class="form-group">
<label for="mobile_number">Mobile Number</label>
<input type="text" name="mobile_number" class="form-control" id="mobile_number" placeholder="Please enter mobile number">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</body>
</html>

Laravel: Login system problem for learning

I'm trying to make a login for learning, so I followed a video from youtube with the same coding. It should be able to check the format of the inputted data, check whether user already login or not, check whether user accessing the next page wihthout login, but in the end, it will always only showed email and password required errors even if I already inputted the right input. Please help. Here are my codes.
web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/main', 'MainController#index');
Route::post('/main/checklogin', 'MainController#checklogin');
Route::get('main/successlogin', 'MainController#successlogin');
Route::get('main/logout', 'MainController#logout');
login.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Login</title>
<!--CSS-->
<link rel="stylesheet" href="{{ asset('css/styles.css') }}" type="text/css">
<link rel="stylesheet" href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' />
<script type="text/javascript" src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
</head>
<body>
<div class="login-page-frame">
<div class="header-login-page-frame">
<h3>Login</h3>
</div>
<div class="inner-login-form-frame">
#if(isset(Auth::user()->email))
<script>window.location="/main/successlogin";</script>
#endif
#if($message = Session::get('error'))
<div class="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert"></button>
<strong>{{$message}}</strong>
</div>
#endif
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ url('/main/checklogin') }}" class="login-form">
{{ csrf_field() }}
<input type="email" placeholder="email" name="login-email" class="form-control">
<br>
<input type="password" placeholder="pass" name="login-password" class="form-control">
<br>
<input type="submit" name="login" class="btn-login" value="login">
</form>
</div>
</div>
</body>
</html>
halamanUtama.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Halaman Utama</title>
</head>
<body>
<div class="container box">
<h3 align="center">Selamat Datang</h3>
<br />
#if(isset(Auth::user()->email))
<div class="alert alert-danger success-block">
<strong>Welcome {{ Auth::user()->email }}</strong>
<br />
Logout
</div>
else
<script>window.location="/main";</script>
#endif
</div>
</body>
</html>
MainController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
use Input;
class MainController extends Controller
{
//
function index(){
return view('login');
}
function checklogin(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
]);
$user_data=array(
'email' => $request->get('login-email'),
'password' => $request->get('login-password')
);
if(Auth::attempt($user_data)){
return redirect('main/successlogin');
}else{
return back()->with('error', 'Wrong Login Details');
}
}
function successlogin(){
return view('halamanUtama');
}
function logout(){
Auth::logout();
return redirect('main');
}
}
I won't comment on whether any of your other code works, but the cause of your validation errors is that the name of your form inputs does not match the name of the fields you are trying to validate.
In your form, your inputs are called login-email and login-password. However, in your controller, you are validating that a field called email and a field called password are provided (because they are required).
So either change your form names to email and password or change your validation fields to login-email and login-password.

RESOLVED: Laravel - Can't make "submit form" route to show up

RESOLVED!
I just needed to access "links.test/submit" instead of simply "links.test", as "submit.blade.php" was a new page.
I also learned the tutorial uses an older version of Laravel, meaning "resources/views/layouts/app.blade.php" was not created because the
php artisan make:auth
command did not work. For Laravel 7, as Gustavo Alves pointed out, I needed to use these two commands instead:
composer require laravel/ui
php artisan ui vue --auth
ORIGINAL QUESTION:
I am going through a Laravel tutorial for beginners - https://laravel-news.com/your-first-laravel-application. I came to the "Displaying the Link Submission Form" section and pasted the provided code snippet into the routes/web.php file, then created submit.blade.php template at resources/views/submit.blade.php with the provided code snippet, as per instructions.
However, the submit form is NOT showing up in my "links.test".
web.php:
?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
$links = \App\Link::all();
return view('welcome', ['links' => $links]);
});
Route::get('/submit', function () {
return view('submit');
});
submit.blade.php:
#extends('layouts.app')
#section('content')
<div class="container">
<div>
<h1>Submit a Link </h1>
<form action="/submit" method="post" >
#if ($errors->any())
<div class="alert alert-danger" role="alert">
Plese fix the following errors
</div>
#endif
{!!csrf_field()!!}
<div class="form-group{{ $errors->has('title') ? 'has-error' : ''}}">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title" value="{{ old('title') }}">
#if($errors->has('title'))
<div class="alert alert-danger">
{{ $errors->first('title') }}
</div>
#endif
</div>
<div class="form-group{{ $errors->has('url') ? ' has-error' : '' }}">
<label for="url">Url</label>
<input type="text" class="form-control" id="url" name="url" placeholder="URL" value="{{ old('url') }}">
#if($errors->has('url'))
<span>
<div class="alert alert-danger">
{{ $errors->first('url') }}
</div>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('description') ? ' has-error' : '' }}">
<label for="description">Description</label>
<textarea class="form-control" id="description" name="description" placeholder="description">{{ old('description') }}</textarea>
#if($errors->has('description'))
<div class="alert alert-danger">
{{ $errors->first('description') }}
</div>
#endif
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
#endsection
So, what I can gather for your comment is
you need to create resources\views\layouts\app.blade.php where you will have something like this
<!DOCTYPE html>
<html lang="en">
<head>
<title>Your App</title>
#section('head')
<!-- Styles -->
<link href="{{ mix('css/app.css') }}" rel="stylesheet">
#show()
</head>
<body>
#yield('content')
#section('scripts')
<script src="{{ mix('/js/app.js') }}"></script>
#show
#endsection
</body>
</html>
Once you got this you should be able to extend and this should work as well.

The email field is required but no input email in view Laravel

I keep getting this error message:
The email field is required.
But I don't have any input type with a name of email in my view:
Login
<link rel="shortcut icon" href="{{ asset('img/logo.png') }}" type="image/x-icon">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,800" rel="stylesheet">
<link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}">
<link rel="stylesheet" href="{{ asset('css/feather.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
<link rel="stylesheet" href="{{ asset('css/jquery.mCustomScrollbar.css') }}">
</head>
<body>
<section class="login-block">
<div class="container">
<div class="row">
<div class="col-md-12">
<form action="/login" method="post" class="md-float-material form-material">
#csrf
<div class="auth-box card">
<div class="card-block">
<div class="row m-b-20">
<div class="col-md-12">
<h3 class="text-center">Members Management System</h3>
</div>
</div>
#if ($errors)
<div class="alert alert-danger background-danger">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<i class="icofont icofont-close-line-circled text-white"></i>
</button>
#foreach ($errors->all() as $error)
- {{ $error }}
<br>
#endforeach
</div>
#endif
<div class="form-group form-primary">
<input type="text" name="employee_id" class="form-control" required=""
placeholder="Employee ID">
<span class="form-bar"></span>
</div>
<div class="form-group form-primary">
<input type="password" name="password" class="form-control" required=""
placeholder="Password">
<span class="form-bar"></span>
</div>
<div class="row m-t-30">
<div class="col-md-12">
<button type="submit"
class="btn btn-primary btn-md btn-block waves-effect waves-light text-center m-b-20">
SIGN IN
</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
<script src="{{ asset('js/jquery.min.js') }}"></script>
<script src="{{ asset('js/jquery-ui.min.js') }}"></script>
<script src="{{ asset('js/script.js') }}"></script>
</body>
</html>
I don't understand why the $errors is notifying me of error regarding email. Any suggestions? I didn't modify any default AUTH settings from Laravel. It may seem that the error is coming from other source?
EDIT:
Thanks for suggesting to override the username() in my LoginController by:
public function username()
{
return 'employee_id';
}
Is this the most conventional and preferred way to do this? Thank you for the assist.
AuthenticatesUsers is responsible for validating the data after the user submitted the form. If you take a look at this file, you will see this method:
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
More specifically, as you can see, this method is in charge for calling the validator on the fields name "password" and by the method username(). If you only wanted to custom the username field, you could overwrite the username() method in LoginController class:
public function username()
{
return 'employee_id';
}
But since you want to custom both the username field name and the password field name, I suggest that you overwrite the validateLogin() method in the LoginController class:
protected function validateLogin(Request $request)
{
$this->validate($request, [
'employee_id' => 'required|string',
'user_password' => 'required|string',
]);
}
Hope that helps.
You can refer employee_id, as username, on login.
Now, open LoginController, and add the username() method.
public function username() {
return "username";
}
Now, you can login without e-mail address.

return withSuccess withErrors lost

I'm using a request validation to validate my form post which works fine for a "simple" contact class but not for my posts class.
Working:
ContractController GET:
public function showForm()
{
return view('contact');
}
ContractController POST:
public function sendContactInfo(ContactRequest $request)
{
blabla
return back()
->withSuccess("Thank you");
}
not working:
postcontroller GET:
public function changepost($postid)
{
$postdetail = posts::find($postid);
blabla
return view('changepost')->with("postdetail", $postdetail);
}
postcontroller POST:
public function changepostvalues(changepostreqeust $request)
{
blabla
return back()->withSuccess("Thank you");
}
withSuccess and withError is only stored for the next request, correct?
I've also tried to use Session:flash with the same result, success and error are not in the session.
when I try Session::put all work fine. however I don't want to store the messeage permanently in the session and I also want to understand why the infromations are lost...
I believe it has something to do with the return view('changepost')->with("postdetail", $postdetail); where I need to pass also the error and success messages....
Thanks.
EDIT
Add View
#extends('master')
#section('title', 'lala')
#section('sidebar')
#parent
#endsection
#section('page-script')
<link href="{{ asset('/packages/dropzone/dropzoneaddpost.css') }}" rel="stylesheet">
#foreach($images as $image)
<meta name="postimage" content="{{$image->image_path}}" id="{{$image->id}}">
#endforeach
#stop
#section('content')
<div align="center">
<div class="addpost">
#if (Session::has('success'))
<div class="alert alert-info">{{ Session::get('success') }}</div>
#endif
<div class="row">
<div class="files" id="previews">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail /></span>
</div>
<div>
<strong class="error text-danger" data-dz-errormessage></strong>
</div>
<div style="text-align: center;">
<button data-dz-remove class="btn delete mydelbutton">
<i class="glyphicon glyphicon-trash"></i>
</button>
</div>
</div>
</div>
</div>
<div class="row">
<form action="/changepost" method="post">
<div class="form-group">
<label for="txttitle">Titel:</label>
<input class="form-control" id="txttitle" type="text" name="beschreibung" id="beschreibung" maxlength="45" style="" value='{{ $postdetail->beschreibung }}'>
<label for="txtmessage">Beschreibung:</label>
<textarea id="txtmessage" class="form-control" rows="5" name="description" id="description" maxlength="500">{{$postdetail->text}}</textarea>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="postid" value="{{ $postdetail->id }}">
<button id="savepost" class="btn mybutton start">
<i class="glyphicon glyphicon-upload"></i>
<span>Save</span>
</button>
</form>
</div>
</div>
</div>
</div>
<script src="{{ asset('/packages/dropzone/dropzone.js') }}"></script>
<script src="{{ asset('/packages/dropzone/dropzone-config.js') }}"></script>
#stop

Resources