SigalZ started a new conversation+100 XP
1w ago
Hello,
I installed yajra datatables version 12 on my laravel 12 project.
I have a few questions and I just don't understand the documentation.
- On the Quick Starter instructions, it says:
"Next, we will install Laravel DataTables Vite to simplify our frontend setup.
npm i laravel-datatables-vite --save-dev
This will install the following packages:
- Bootstrap Icons
- DataTables with Buttons and Select plugins for Bootstrap 5
- Laravel DataTables custom scripts
Once installed, we can now configure our scripts and css needed for our application. resources/js/app.js
import './bootstrap'; import 'laravel-datatables-vite';
resources/sass/app.scss
// Fonts @import url('https://fonts.bunny.net/css?family=Nunito');
// Variables @import 'variables';
// Bootstrap @import 'bootstrap/scss/bootstrap';
// DataTables
@import 'bootstrap-icons/font/bootstrap-icons.css'; // This does not exist
@import "datatables.net-bs5/css/dataTables.bootstrap5.min.css";
@import "datatables.net-buttons-bs5/css/buttons.bootstrap5.min.css";
@import 'datatables.net-select-bs5/css/select.bootstrap5.css';
There is no folder called: bootstrap-icons anywhere. What am I missing?
- How do I show a relationship value?
e.g. I have a table called green_beans, in the table there is a column: country_id which is a relationship to countries table. I need to display the country's name.
public function getColumns(): array
{
return [
Column::make('id'),
Column::make('country_id'), // should be country name from countries table.
Column::make('name'),
Column::make('stock'),
Column::computed('action')
->exportable(false)
->printable(false)
->width(60)
->addClass('text-center'),
];
}
- How do I add an Edit button on each row that will open the Edit page for that green bean. How do I get the green bean id here?
public function dataTable(QueryBuilder $query): EloquentDataTable
{
return (new EloquentDataTable($query))
->addColumn('action', "<a href='greenbean/'" . green_bean->id // what do I put here? . " class='btn btn-sm btn-primary'>Edit</a>")
->setRowId('id');
}
- Why don't I see any of these buttons (excel, csv, pdf, etc.):
public function html(): HtmlBuilder
{
return $this->builder()
->setTableId('greenbeans-table')
->columns($this->getColumns())
->minifiedAjax()
->orderBy(1)
->selectStyleSingle()
->buttons([
Button::make('excel'),
Button::make('csv'),
Button::make('pdf'),
Button::make('print'),
Button::make('reset'),
Button::make('reload')
]);
}
The full code:
In the controller:
public function index(GreenBeansDataTable $dataTable)
{
return $dataTable->render('admin.green-beans.index');
}
GreenBeanDataTable:
<?php
namespace App\DataTables;
use App\Models\GreenBean;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Html\Builder as HtmlBuilder;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
class GreenBeansDataTable extends DataTable
{
protected array $actions = ['myEdit'];
/**
* Build the DataTable class.
*
* @param QueryBuilder<GreenBean> $query Results from query() method.
*/
public function dataTable(QueryBuilder $query): EloquentDataTable
{
return (new EloquentDataTable($query))
//->addColumn('action', 'greenbeans.action')
->addColumn('action', "<a href='greenbean/'" . $query->id . " class='btn btn-sm btn-primary'>Edit</a>")
->setRowId('id');
}
/**
* Get the query source of dataTable.
*
* @return QueryBuilder<GreenBean>
*/
public function query(GreenBean $model): QueryBuilder
{
return $model->newQuery();
}
/**
* Optional method if you want to use the html builder.
*/
public function html(): HtmlBuilder
{
return $this->builder()
->setTableId('greenbeans-table')
->columns($this->getColumns())
->minifiedAjax()
->orderBy(1)
->selectStyleSingle()
->buttons([
Button::make('excel'),
Button::make('csv'),
Button::make('pdf'),
Button::make('print'),
Button::make('reset'),
Button::make('reload')
]);
}
/**
* Get the dataTable columns definition.
*/
public function getColumns(): array
{
return [
Column::make('id'),
Column::make('country'),
Column::make('name'),
Column::make('stock'),
Column::computed('action')
->exportable(false)
->printable(false)
->width(60)
->addClass('text-center'),
];
}
/**
* Get the filename for export.
*/
protected function filename(): string
{
return 'GreenBeans_' . date('YmdHis');
}
}
Please help.
SigalZ wrote a reply+100 XP
2w 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
2w 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
3w 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
3w ago
Thank you very much, that was it :)
SigalZ liked a comment+100 XP
3w 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
3w ago
Thank you but that's not the problem, the package changes the column names to lowercase.
SigalZ started a new conversation+100 XP
3w 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
3w ago
Thank you very much for trying to help. imrandevbd's reply solved my problem.
SigalZ liked a comment+100 XP
3w 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
3w 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
3w 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
3w 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
6mos 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?