Laravel: Login system problem for learning - laravel

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.

Related

How to upload image to Laravel storage?

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>

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>

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.

Twitter API app, does not showing pictures or videos

I created Twitter API app in Laravel. The application provide very weird layout. I cannot set up profile picture, or picture for tweet. I am getting only text pretty much.
I spent whole day to figure out, why my APP does not have picture, url or videos.
I appreciate any suggestions what might be wrong
<!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">
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="sha384-
UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/"
crossorigin="anonymous">
<link rel="stylesheet" href="{{asset('/css/app.css')}}">
<title>Nancy's Twitter API App</title>
</head>
<body>
<h1 class="text-info text-center mt-5">Nancy's Tweets Api</h1>
<div class="container">
<div class="col align-self-center mb-5">
<form class="well" action="{{route('post.tweet')}}"
method="POST" enctype="multipart/form-data">
#csrf
#if(count($errors) > 0)
#foreach ($errors->all() as $error)
<div class="alert alert-danger"> {{$error}}</div>
#endforeach
#endif
<div class="form-group">
<label>Your Tweet</label>
<textarea class="form-control" name="tweet"
rows="3"></textarea>
</div>
<div class="form-group">
<label>Upload Filet</label>
<input type="file" class="form-control-file"
name="images[]" multiple>
</div>
<div class="from-group">
<button class="btn btn-success">Create
Tweet</button>
</div>
</form>
</div>
</div>
<div class="container">
<h3>Tweets:</h3>
#if(!empty($data))
#foreach ($data as $key => $tweet )
<div class="card text-primary bg-white mb-3" style="max-width:
150rem;">
<div class="card-body">
<p class="card-text"><h3>{{$tweet->text}}</h3></p>
#if(!empty($tweet->extented_entities->media)){
#foreach ($tweet->extented_entities->media as $i)
<img src="{{$i->media_url_https}}"
style="width:100px;">
#endforeach}
#endif
<div class="card-header">
<i class="fas fa-heart">{{$tweet-
>favorite_count}}</i>
<i class="fas fa-redo"> {{$tweet-
>retweet_count}}</i>
</div>
</div>
</div>
#endforeach
#else
<p>No Tweets Found</p>
#endif
</div>
</body>
</html>
class TwitterController extends Controller
{
//
public function twitterUserTimeline(){
$count = 10;
$format = 'array';
$data = Twitter::getUserTimeline([$count, $format]);
return view('twitter', compact('data'));
}
public function tweet(Request $request){
$this->validate($request, [
'tweet' => 'required'
]);
$newTweet = ['status' => $request->tweet];
if(!empty($request->images)){
foreach($request->images as $key => $value){
$uploadMedia = Twitter::uploadMedia(['media' => File::get($value-
>getRealPath())]);
if(!empty($uploadMedia)){
$newTweet['media_ids'][$uploadMedia->media_id_string] =
$uploadMedia->media_id_string;
}
}
}
$twitter = Twitter::postTweet($newTweet);
return back();
}
}

laravel using withErrors in a try catch

So i'm making this website where you can buy game consoles, so I made a crud, but I wanted that it was impossible to insert duplicates in the database, but when I create a dupicate you get a laravel error and that is not user friendly. So I wanted to show a normal message saying that you made a duplicate. so I made this.
public function store(Request $request)
{
try
{
$consoles = new consoles();
$consoles->naam = input::get('naam');
$consoles->releasedate = input::get('releasedate');
$consoles->company = input::get('company');
$consoles->price = input::get('price');
$consoles->created_at = null;
$consoles->updated_at = null;
$consoles->save();
}catch (\Exception $e)
{
return Redirect::to('console/create')
->withInput()
->withErrors(array('message' => 'duplicate'));
}
return redirect('consoles');
}
the problem is that ->withErrors(array('message' => 'duplicate')) doesn't show anything. what am I doing wrong.
EDIT
create.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker({ dateFormat: 'yy-mm-dd' }).val();
} );
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading"> creating data</div>
<form method="POST" action="{{url('games/store/')}}">
naam: <br>
<input type="text" name="naam" required>*required<br>
releasedate: <br>
<input type="text" name="releasedate" id="datepicker" required>*required<br>
company: <br>
<input type="text" name="company" required>*required<br>
price: <br>
<input type="number" name="price" min="0" value="0" step=".01" required>*required<br>
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<input type="submit" name="create" value="create">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
When you set withErrors you don't need to pass the array, just write the error message like this ->withErrors('Duplicate');
In the view remember to include a check if there are errors
#if ($errors->count())
<div class="col-md-12">
<div class="alert alert-danger text-center">
#foreach ($errors->all() as $error)
<p>{{$error}}</p>
#endforeach
</div>
</div>
#endif
You can simply use with() to send the message to the view like
return Redirect::to('console/create')
->withInput()
->with('message', 'duplicate');
and access that in view as
#if ($message = Session::get('message'))
{{$message}}
#endif

Resources