SigalZ wrote a reply+100 XP
20h ago
Ok, I managed to solve the issue and add the validation to the errors. So now I get it as a normal validation error, not using Swal.
If anyone is interested, in my Import class I added these methods:
private function findDuplicate($data)
{
$find_duplicate = false;
foreach ($data as $key => $val) {
$date = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($val['time'])->format('Y-m-d H:i:00');
//get coffee name
$dets = explode("-", $val['profile']);
$coffee_name = $dets[0];
$coffee_id = Coffee::where('short_name', $coffee_name)->value('id');
$find_duplicate = Roast::where('roast_date_time', $date)
->where('coffee_id', $coffee_id)->count();
if ($find_duplicate)
return $key;
}
return 0;
}
public function withValidator(Validator $validator)
{
$validator->after(function ($validator) {
// Your custom logic here
$row_no = $this->findDuplicate($validator->getData());
if ($row_no != 0) {
$validator->errors()->add("$row_no", 'This roast date and coffee already exists in the database.');
}
});
}
}
SigalZ wrote a reply+100 XP
20h ago
Yes, it is included in: resources/views/layouts/master.blade.php:
@include('layouts.admin.scripts')
@include('sweetalert2::index')
</body>
</html>
There are no errors in the console.
SigalZ started a new conversation+100 XP
23h ago
Hello, Using laravel 12 and the package: Laravel Excel.
https://docs.laravel-excel.com/3.1/imports/validation.html
I have an excel file with these column names:
Batch, Time, Profile, Beans, In (g), Out (g)
Example for the Time value: 2026-05-17 13:39
Example for the Profile value: Brazil-5kg-Med-03
I need to check a table in the database for existing records for:
roasted_date: 2026-05-17 13:39:00
coffee_id: 3
If a record exists, I need to give an error.
In my import class I have this method:
public function collection(Collection $rows)
{
foreach ($rows as $row) {
$date = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['time'])->format('Y-m-d H:i:00');
$dets = explode("-", $row['profile']);
$coffee_name = $dets[0];
$coffee_id = Coffee::where('short_name', $coffee_name)->value('id');
$find_duplicate = Roast::where('roast_date_time', $date)
->where('coffee_id', $coffee_id)->count();
if ($find_duplicate > 0) {
Swal::fire([
'title' => 'Error',
'text' => "Profile already uploaded",
'icon' => 'error',
]);
Log::debug('error');
return redirect()->route('warehouse.upload-roasts');
}
public function rules(): array
{
return [
'out_g' => ['exclude_if:*.batch,SUM', 'required', 'numeric'],
'beans' => ['exclude_if:*.batch,SUM', 'required', 'exists:green_beans,name'],
'profile' => function (string $attribute, mixed $value, Closure $fail) {
$dets = explode("-", $value);
$coffee_name = $dets[0];
$coffee = Coffee::where('short_name', $coffee_name)->first();
if (is_null($coffee)) {
$fail("The coffee name is invalid.");
}
},
];
}
It finds a duplicate (I get the Log debug message), but I don't get the Swal message.
I couldn't find a way to add this validation to the validation errors in the documentation, or I don't really understand their examples for complex validations, that's why I'm trying it that way.
Can someone please help?
SigalZ wrote a reply+100 XP
1d ago
Thank you very much, that was it :)
SigalZ liked a comment+100 XP
1d ago
Look here: https://docs.laravel-excel.com/3.1/imports/validation.html#validating-with-a-heading-row
If your validation rules reference other field names, ... the field name must be prefixed with *.
So try this:
'beans' => ['exclude_if:*.batch,SUM', ...
SigalZ wrote a reply+100 XP
1d ago
Thank you but that's not the problem, the package changes the column names to lowercase.
SigalZ started a new conversation+100 XP
1d ago
Hello, Using laravel 12 and the package: Laravel Excel.
https://docs.laravel-excel.com/3.1/imports/validation.html
I have an excel file with these column names:
Batch, Time, Profile, Beans, In (g), Out (g)
I need to validate rows only if the value in the Batch column is not: SUM
The problem I have is that the validations happen even if the value in the column is SUM. I get the errors on the row where the value in the column Batch is SUM.
I tried 3 different ways:
My import class:
<?php
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use App\Models\Coffee;
use App\Models\GreenBean;
use Illuminate\Support\Facades\Log;
class RoastImport implements ToCollection, WithHeadingRow, WithValidation
{
private $bean;
/**
* @param Collection $rows
*/
public function collection(Collection $rows)
{
foreach ($rows as $row) {
$name = $row['profile'];
$weight = $row['out_g'];
}
}
public function rules(): array
{
return [
'beans' => ['exclude_if:batch,SUM', 'required', 'exists:green_beans,name'],
'out_g' => ['exclude_if:batch,SUM', 'required', 'numeric'],
];
//I also tried:
return [
'out_g' => Rule::when([fn($input) => $input->batch != 'SUM', ['required', 'numeric']),
'beans' => Rule::when(fn($input) => $input->batch != 'SUM', ['required', 'exists:green_beans,name']),
]
//and
return [
'out_g' => Rule::when(fn($input) => $input['batch'] != 'SUM', ['required', 'numeric']),
'beans' => Rule::when(fn($input) => $input['batch'] != 'SUM', ['required', 'exists:green_beans,name']),
];
}
}
Please help.
SigalZ wrote a reply+100 XP
1d ago
Thank you very much for trying to help. imrandevbd's reply solved my problem.
SigalZ liked a comment+100 XP
1d ago
That error is popping up because you're adding a manual error to the validator without a numeric key. Laravel Excel expects the attribute name to follow a specific pattern (like row_number.column) so it can parse the row index. When you just pass 'Green Bean', strtok fails to find a numeric row index, passing a string to the Failure constructor instead.
Also, your current logic for checking the bean in the collection method won't work for validation because rules() and withValidator() run before the collection() method even touches the data.
namespace App\Imports;
use Maatwebsite\Excel\Concerns\ToCollection; use Maatwebsite\Excel\Concerns\WithHeadingRow; use Maatwebsite\Excel\Concerns\WithValidation; use Illuminate\Support\Collection;
class RoastImport implements ToCollection, WithHeadingRow, WithValidation { public function collection(Collection $rows) { // Your import logic here }
public function rules(): array
{
return [
// 'beans' matches the slugified header 'Beans'
'beans' => ['required', 'exists:green_beans,name'],
// 'out_g' matches 'Out (g)'
'out_g' => ['required', 'numeric'],
];
}
public function customValidationMessages()
{
return [
'beans.exists' => 'The selected Green Bean is invalid.',
'out_g.required' => 'The Out (g) column cannot be empty.',
];
}
}
SigalZ wrote a reply+100 XP
3d ago
Hi all,
Thank you very much for all the help.
For some reason, after restarting my computer this morning, the site works.
"Have you tried switiching it off and on again?....."
Have a beautiful weekend
SigalZ started a new conversation+100 XP
4d ago
Hello,
Using Laravel 12, I cloned my github repository into c:\wamp64\www
I ran: composer install
composer update
npm install
I copied my .env file from a previous folder I had for this project.
I ran yarn dev, got these errors:
(!) Failed to run dependency scan. Skipping dependency pre-bundling. Error: failed to resolve rollupOptions.input value: "resources/admin/sass/admin.scss". at resolvePath (file:///C:/wamp64/www/mysite.local/node_modules/vite/dist/node/chunks/config.js:31449:29) at async Promise.all (index 2) at async computeEntries (file:///C:/wamp64/www/mysite.local/node_modules/vite at async scan (file:///C:/wamp64/www/mysite.local/node_modules/vite/dist/node/chunks/config.js:31388:19) at async file:///C:/wamp64/www/mysite.local/node_modules/vite/dist/node/chunks/config.js:34131:15
I have the right database credentials and the actual database.
Trying to run the site in the browser, I get this message:
Looks like there’s a problem with this site
Firefox can’t connect to the server at mysite.local What can you do about it?
Try connecting on a different device. Check your modem or router. Disconnect and reconnect to Wi-Fi.
What am I doing wrong please?
SigalZ started a new conversation+100 XP
1w ago
Hello, Using laravel 12 and the package: Laravel Excel.
https://docs.laravel-excel.com/3.1/imports/validation.html
I have an excel file with these column names:
Batch, Time, Profile, Beans, In (g), Out (g)
I need to check that the value in the 'Beans' column exists in the database and that there is a value in the 'Out (g)' column.
The documentation says:
"Configuring the validator
If you want to add conditional validation or complex validation that cannot be expressed through rules you can configure the validator similar to how you would do this with a Form request (opens new window)
Manual validation
You can use $validator->getData() to get access to the data under validation
class UsersImport implements WithValidation
{
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add('field', 'Something is wrong with this field!');
}
});
// or...
$validator->sometimes('*.email', 'required', $this->someConditionalRequirement());
}
}
"
When I test it, I get this error:
TypeError vendor\maatwebsite\excel\src\Validators\Failure.php:36
Maatwebsite\Excel\Validators\Failure::__construct(): Argument #1 ($row) must be of type int, string given, called in C:\wamp64\www\mysite.local\vendor\maatwebsite\excel\src\Validators\RowValidator.php on line 55
In my blade:
@if ($errors->any())
<div class="alert alert-danger">
<p>There are errors in the file you uploaded</p>
<ul>
@foreach ($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
</div>
@endif
My Import class:
<?php
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use App\Models\GreenBean;
class RoastImport implements ToCollection, WithHeadingRow, WithValidation
{
private $bean;
/**
* @param Collection $rows
*/
public function collection(Collection $rows)
{
foreach ($rows as $row) {
$this->bean = GreenBean::where('name', $row['beans'])->first();
}
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'out_g' => 'required',
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
if (!$this->bean) {
$validator->errors()->add('Green Bean', 'The Green Bean is invalid');
}
});
if ($validator->fails()) {
return redirect()->route('warehouse.upload-roasts');
}
}
public function customValidationMessages()
{
return [
'out_g.required' => 'The :attribute column cannot be empty',
];
}
}
Can anyone please help?
SigalZ started a new conversation+100 XP
5mos ago
I am trying to use realrashid/sweetalert2 in laravel 12.
I installed the package and in my blade I have this code:
<!DOCTYPE html>
<html lang="en">
<head>
@include('layouts.meta')
<title>Home | {{ config('app.name') }}</title>
@vite(['resources/sass/app.scss', 'resources/js/app.js'])
</head>
<body data-bs-spy="scroll" data-bs-target="#navbarNav" data-bs-offset="80" tabindex="0">
... some html...
@include('sweetalert::alert')
<script src="https://kit.fontawesome.com/5fb9c0ddb1.js" crossorigin="anonymous"></script>
<script src="https://snapwidget.com/js/snapwidget.js"></script>
</body>
In my app.js:
import './bootstrap';
import Swal from 'sweetalert2'
window.Swal = Swal
I get the error:
GET http://highlandnew.local/vendor/sweetalert/sweetalert.all.js [HTTP/1.1 404 Not Found 136ms]
Uncaught ReferenceError: Swal is not defined
I looked at: vendor/realrashid/sweet-alert/resources/views/alert.blade.php it has this line:
<script src="{{ $cdn ?? asset('vendor/sweetalert/sweetalert.all.js') }}"></script>
There is no folder vendor/sweetalert, there is folder: vendor/realrashid/sweet-alert...
So I published the package assets, and now I have:
resources\views\vendor\sweetalert\alert.blade.php and public\vendor\sweetalert\sweetalert.all.js
but now, this line:
@include('sweetalert::alert')
does not include the alert view in the blade, and of course I'm getting the Swal not defined error again.
What am I missing?
SigalZ liked a comment+100 XP
5mos ago
Nothing goes to an admin route; you're crashing the app when Laravel is trying to register routes:
dd('admin');
Add the route definitions instead of a dd() call.
SigalZ wrote a reply+100 XP
5mos ago
Ok, I found a way to make it all work.
In the app.php file I add the admin.php route file into the web route:
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: [
__DIR__ . '/../routes/web.php',
__DIR__ . '/../routes/admin.php'
],
And in my admin.php I removed the dd('admin') which caused errors and put a route call to a controller:
Route::middleware(AdminMiddlware::class)->prefix('admin')->name('admin.')->group(function () {
Route::get('/dashboard', [AdminController::class, 'index'])->name('dashboard');
});
SigalZ wrote a reply+100 XP
5mos ago
SigalZ wrote a reply+100 XP
5mos ago
Thank you.
I tried your second solution so now my web.php has this code:
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\ContactController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\PagesController;
Auth::routes();
require __DIR__ . '/admin.php';
Route::get('/', [HomeController::class, 'index'])->name('home');
My admin.php file:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Middleware\AdminMiddlware;
Route::middleware(AdminMiddlware::class)->prefix('admin')->name('admin.')->group(function () {
dd('admin');
})->name('dashboard');
app.php
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__ . '/../routes/web.php',
commands: __DIR__ . '/../routes/console.php',
health: '/up',
/*then: function () {
Route::middleware(AdminMiddlware::class)
->prefix('admin')
->name('adminn.')
->group(base_path('routes/admin.php'));
},*/
)
->withMiddleware(function (Middleware $middleware): void {
//
$middleware->append(ProtectAgainstSpam::class);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();
Now I can't browse anywhere besides the admin dashboard, e.g. if I put the sites home page in the browser's address, it still goes to the admin route instead of the home page and I get this error on VS code:
2025-11-24 11:24:00.382 [info] Laravel Extra Intellisense command started: Application Models 2025-11-24 11:24:00.383 [info] Laravel Extra Intellisense command started: Auth Data 2025-11-24 11:24:02.053 [error] Laravel Extra Intellisense Error: Auth Data
"admin" // routes\admin.php:14
2025-11-24 11:24:02.059 [error] Laravel Extra Intellisense Error: Application Models
"admin" // routes\admin.php:14
Can you please help?
SigalZ started a new conversation+100 XP
6mos ago
Using Laravel 12, I have a custom routes file.
All the routes in this file should be blocked to guests and users that don't have a specific permission.
I can't make the middlware work correctly.
The user I am testing has the permission 'admin dashboard' through the 'admin' role.
The routes file: routes/admin.php:
use Illuminate\Support\Facades\Route;
Route::get('/dashboard', function () {
dd('admin');
})->name('dashboard');
In bootstrap/app.php:
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__ . '/../routes/web.php',
commands: __DIR__ . '/../routes/console.php',
health: '/up',
then: function () {
Route::middleware( 'admin')
->prefix('admin')
->name('admin.')
->group(base_path('routes/admin.php'));
},
)
->withMiddleware(function (Middleware $middleware): void {
//
$middleware->append(ProtectAgainstSpam::class);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();
In App/Http/Middleware/AdminMiddleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;
class AdminMiddlware
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
//Tried
if (! $request->user() || ! $request->user()->can('admin dashboard')) {
//And Tried
if (! Auth::user() || ! Auth::user()->can('admin dashboard')) {
abort(403, 'Unauthorized action.'); // Or redirect to a different page
}
return $next($request);
}
}
Even though the user is logged in and has the permission, I get the Unauthorized page.
using: dd(Auth::user()) or dd($request->user()) both return null.
Can anyone help please?