Laravel 5.7.17 file validation issue - laravel

The example is based on Laravel's registration.
I have added following to register.blade.php:
<div class="form-group row">
<label for="file" class="col-md-4 col-form-label text-md-right">{{ __('Files') }}</label>
<div class="col-md-6">
<input type="file" id="files" name="files[]" multiple>
</div>
</div>
The method in RegisterController looks like this:
protected function validator(array $data)
{
$validator = Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'files.*' => ['required', 'file'],
]);
dd($validator->errors());
}
I'm trying to upload a PDF and a DOC file.:
MessageBag {#236 ▼
#messages: array:2 [▼
"files.0" => array:1 [▼
0 => "The files.0 must be a file."
]
"files.1" => array:1 [▼
0 => "The files.1 must be a file."
]
]
#format: ":message"
}
Must be a file? These are files...

just add enctype="multipart/form-data" to your form:
<form method="POST" action="{{ route('register') }}" enctype="multipart/form-data">

Try this :
protected function validator(array $data)
{
$validator = Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'files.*' => ['required', 'mimes:doc,docx,pdf,txt'],
]);
dd($validator->errors());
}

Related

Always show [The post image must be a file of type: jpg, jpeg, png, webp.] laravel

It always shows error in validation. I tried uploading png jpeg jpg and all showed error.
View
<form action="{{ route('post.store') }}" method="POST" enctype="multipart/form-data">
<div id="post_image_container">
<input type="file" name="post_image[]" id="post_image" class="bg bg-light border rounded text-dark font w-100 p-3 form-control" placeholder="Add Images" accept="image/*" multiple>
#if($errors->first('post_image'))
<small class="form-text d-block text-danger fw-bold">{{ $errors->first('post_image') }}
</small>
#endif
</div>
Controller - Validation
$this->validate($request, [
'post_title' => ['required', 'min:5'],
'post_tags' => ['required', 'min:5'],
'post_content' => ['required', 'min:50'],
'post_image' => ['required', 'mimes:jpg,jpeg,png,webp']
]);
dd($request->all());
You are uploading multiple images, therefore, you need to state that in your validating by writing this:
$this->validate($request, [
'post_title' => ['required', 'min:5'],
'post_tags' => ['required', 'min:5'],
'post_content' => ['required', 'min:50'],
'post_image' => ['required', 'array'],
'post_image.*' => ['required', 'mimes:jpg,jpeg,png,webp'],
]);

laravel 9 has defferent location then i set, and every file i put become .tmp

i dont understand why, i do it in laravel 8 and it work but not in laravel 9
Store function
public function store(Request $request)
{
$ValidatedData = $request->validate([
'title' => 'required|max:255',
'slug' => 'required|unique:menus',
'categories_id' => 'required',
'deskripsi' => 'required',
'is_order' => 'required',
'most' => 'required',
'price' => 'required',
'image' => 'image|file|max:1024'
]);
if($request->file('image')){
$validatedData['image'] = $request->image->store('menus');
}
$ValidatedData['users_id'] = Auth::user()->id;
$ValidatedData['excerpt'] = Str::limit(strip_tags($request->deskripsi), 100);
Menus::create($ValidatedData);
return Redirect('/dashboard/menus')->with('success', 'Tugas Baru Telah Ditambahkan!');
}
Form
<div class="mb-3">
<label for="image" class="form-label">Size Max. 1mb</label>
<input class="form-control #error('image') is-invalid #enderror" type="file"
name="image" id="image">
#error('image')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
.env
FILESYSTEM_DISK=public
After Create the storage location is change

Laravel authentication problem with multiple guards

im new to laravel and im trying to create login function with multiple guards. However when i insert the correct credentials in the form, it does not authenticate properly. I cant seem to find the problem with my login controller, any ideas?
This is my AdminLoginController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin');
}
public function showLoginForm()
{
return view('auth.admin-login');
}
public function login(Request $request)
{
// validate the form data
$this->validate($request, [
'admin_email ' => 'required|email',
'password' => 'required|min:8'
]);
//attempt to log the user in
if( Auth::guard('admin')->attempt(['admin_email'=>$request->admin_email, 'admin_password'=>$request->admin_password], $request->remember))
{
//if successful then send to their location
return redirect()->route('admin.dashboard');
}
//if fail redirect back to the login with the data
return redirect()->back()->withInput($request->only('admin_email','remember'));
}
}
This one is my form
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Admin-Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.login.submit') }}">
#csrf
<div class="row mb-3">
<label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email Address') }}</label>
<div class="col-md-6">
<input id="admin_email" type="email" class="form-control #error('admin_email') is-invalid #enderror" name="admin_email" value="{{ old('admin_email') }}" required autocomplete="admin_email" autofocus>
#error('admin_email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-3">
<label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="admin_password" type="password" class="form-control #error('admin_password') is-invalid #enderror" name="admin_password" required autocomplete="current-admin_password">
#error('admin_password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-3">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
#if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
#endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
This one is the Model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class Admin extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $guard = 'admin';
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'admin_email',
'admin_password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'admin_password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Edited: This is my route
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::prefix('admin')->group(function (){
Route::get('/login', [App\Http\Controllers\Auth\AdminLoginController::class, 'showLoginForm'])->name('admin.login');
Route::post('/login', [App\Http\Controllers\Auth\AdminLoginController::class, 'login'])->name('admin.login.submit');
Route::get('/', [App\Http\Controllers\adminController::class, 'index'])->name('home')->name('admin.dashboard');
});
my dd($request)
Illuminate\Http\Request {#43 ▼
#json: null
#convertedFiles: null
#userResolver: Closure($guard = null) {#260 ▶}
#routeResolver: Closure() {#268 ▶}
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#45 ▶}
+request: Symfony\Component\HttpFoundation\InputBag {#44 ▶}
+query: Symfony\Component\HttpFoundation\InputBag {#51 ▶}
+server: Symfony\Component\HttpFoundation\ServerBag {#47 ▶}
+files: Symfony\Component\HttpFoundation\FileBag {#48 ▶}
+cookies: Symfony\Component\HttpFoundation\InputBag {#46 ▶}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#49 ▶}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/admin/login"
#requestUri: "/admin/login"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: Illuminate\Session\Store {#300 ▶}
#locale: null
#defaultLocale: "en"
-preferredFormat: null
-isHostValid: true
-isForwardedValid: true
-isSafeContentPreferred: null
basePath: ""
format: "html"
}
This is my config/auth file
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'resident' => [
'driver' => 'session',
'provider' => 'residents',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
'residents' => [
'driver' => 'eloquent',
'model' => App\Models\Resident::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'residents' => [
'provider' => 'residents',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admin' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],

Form didn't insert data to database properly [Laravel][Eloquent]

I have problem with my code somewhere that make my data $request just didn't passed to my database table (?), I'm not sure what the problem is but every time I try to submit it just redirect back to my create blade view.But when I debug it using dd($request->all()); it have everything it need.
My table have 5 columns, id, book_id, member_id, user_id, borrow_date, return_date
My Model
protected $table = "borrow";
protected $guarded = [];
public $timestamps = false;
// Relationship Book
public function book()
{
return $this->belongsTo('App\Book');
}
// Relationship Member
public function member()
{
return $this->belongsTo('App\Member');
}
My Create Controller
public function create()
{
$book= Book::all();
$member= Member::all();
return view('borrow.create', compact('book', 'member'));
}
public function store(Request $request)
{
$this->validate($request,[
'book_id' => 'required',
'member_id' => 'required',
'user_id' => 'required',
'borrow_date' => 'required',
'return_date' => 'required',
'status' => 'required'
]);
Borrow::create([
'book_id' => $request->book_id,
'member_id' => $request->member_id,
'user_id' => Auth::user()->id,
'borrow_date' => $request->borrow_date,
'return_date' => $request->return_date,
'status' => 'borrowed',
]); return redirect('/borrow');
}
My Create View
<form action="/borrow" method="POST">
#csrf
<div class="form-group row">
<label class="col-sm-2 col-form-label">Book</label>
<div class="col-sm-10">
<select data-placeholder="Enter Book Data"
data-allow-clear="1" name="book_id" id="book_id">
<option></option>
#foreach($book as $value)
<option value="{{ $value->id }}">ISBN {{ $value->isbn }} -
{{ $value->title }} ({{ $value->year }})
</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Member</label>
<div class="col-sm-10">
<select data-placeholder="Enter Member Data"
data-allow-clear="1" name="member_id" id="member_id">
<option></option>
#foreach($member as $value)
<option value="{{ $value->id }}">{{ $value->name }}
#if ($value->gender == 'man')
(M) -
#else
(W) -
#endif
{{ $value->phone }}
</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Borrow Date</label>
<div class="col-sm-10">
<input type="date" class="form-control" name="borrow_date"
id="borrow_date">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Return Date</label>
<div class="col-sm-10">
<input type="date" class="form-control" name="return_date"
id="return_date">
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
dd($request->all());
array:5 [▼
"_token" => "pN3PPQGpT4jmLln59tY3HBiLj27fWgf65ioIYlv0"
"book_id" => "99"
"member_id" => "99"
"borrow_date" => "2021-09-01"
"return_date" => "2021-09-30"
]
Thanks! Sorry if my English and explanation is bad
You are trying to validate a user_id and a status presents in your $request but of course it doesn't.
$this->validate($request,[
'book_id' => 'required',
'member_id' => 'required',
'user_id' => 'required',
'borrow_date' => 'required',
'return_date' => 'required',
'status' => 'required'
]);
You are using Auth::user()->id as user_id and it isn't in $request
So, just remove 'user_id' => 'required', from validation. You also don't have status in your $request so you need to remove it too. It should be like this;
$this->validate($request,[
'book_id' => 'required',
'member_id' => 'required',
'borrow_date' => 'required',
'return_date' => 'required',
]);
Use fillable in Peminjaman model
protected $fillable = [
'id', 'book_id', 'member_id', 'user_id', 'borrow_date', 'return_date'
];
try to remove user_id and status from the validation, the request doesn't have these parameters, and you are validating them as required values.
$this->validate($request,[
'book_id' => 'required',
'member_id' => 'required',
'borrow_date' => 'required',
'return_date' => 'required',
]);
When using the create() method, you are using what is called massive assignment. As per docs https://laravel.com/docs/8.x/eloquent#mass-assignment:
...before using the create method, you will need to specify either a
fillable or guarded property on your model class. These properties are
required because all Eloquent models are protected against mass
assignment vulnerabilities by default.
Saying that, you have 2 options:
1 - Keep using create() method but define fillable property in your model
protected $fillable = ['id', 'book_id', 'member_id', 'user_id', 'borrow_date', 'return_date'];
2 - Use the save() method with not need to define fillable property:
$borrow = new Borrow();
$borrow->book_id = $request->book_id;
$borrow->member_id = $request->member_id;
$borrow->user_id = Auth::user()->id;
$borrow->borrow_date = $request->borrow_date;
$borrow->return_date = $request->return_date;
$borrow->status = 'borrowed';
$borrow->save();

saving dropdown list value in database laravel

I am trying to ask gender of the user in registration form through dropdown list but I am unable to get that value in controller.
Here is my code to register.blade.php
<!-- Gender -->
<div class="form-group">
<label for="gender" class="col-md-4 control-label">Gender</label>
<div class="col-md-6">
<select class="form-control" required="required">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
Code of register controller
protected function validator(array $data)
{
return Validator::make($data, [
'username' => 'required|string|max:255',
'fullname' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'dob' => 'required|date',
'gender' => 'required|string',
// 'gender' => 'in:male,female'
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
dd($data);
return User::create([
'username' => $data['username'],
'fullname' => $data['fullname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'dob' => $data['dob'],
'gender' => $data['gender'],
]);
}
user model contains
protected $fillable = [
'username', 'email', 'password','fullname','dob','gender'
];
and the output shown when line 'gender' => 'required|string', is commented in validator function of register controller. Nothing happens when this line is uncommented
Write attribute name="gender" in the selectelement.
Without name attribute the data is not passed via GET/POST request.
Name for field was missed.
<select class="form-control" name="gender" required="required">
<option value="male">Male</option>
<option value="female">Female</option>
</select>

Resources