in my e-commerce website, I tried to use darryldecode laravelshoppingcart, and when i Use addToCart fuction in Controller I always get "validation.required" error. And to store the data I use Ajax Request because some of requirements.
PesananController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Meja;
use App\Models\Menu;
use App\Models\DetailPesanan;
use App\Models\Pesanan;
class PesananController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Meja $meja)
{
return view('index', ['meja'=>$meja]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function detail(Meja $meja, Menu $menu)
{
//
return view('detail', ['menu'=>$menu, 'meja'=>$meja]);
}
public function pesan(Request $request, Meja $meja, Menu $menu)
{
\Cart::session($meja->id)->add([
'id' => $request->id,
'name' => $request->nama,
'price' => $request->harga,
'notes' => $request->note,
'quantity' => $request->jumlah,
'attributes' => array(),
]
);
return redirect()->route('menu', [$meja->id]);
}
public function detailPesanan(Meja $meja, Pesanan $pesanan)
{
//
$menu = Menu::all();
$pesanan_detail = DetailPesanan::where('idPesanan', $pesanan->id)->get();
return view('detailPesanan', ['pesanan'=>$pesanan, 'pesanan_detail'=>$pesanan_detail, 'meja'=>$meja]);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
web.php
Route::get('/{meja}/menu', ShowMenu::class)->name('menu');
Route::get('/{meja}/detail/{menu}', [PesananController::class, "detail"])->name('detail');
Route::post('/{meja}/detail/{menu}', [PesananController::class, "pesan"])->name('pesan');
detail.blade.php
#extends('templates.main')
#section('css')
<link href="css/detail.css" rel="stylesheet" >
<link href="css/global.css" rel="stylesheet" >
#endsection
#section('content')
<div class="container-fluid">
<div class="row ">
<div class="col-md-12 p-0 bg-detail ">
<a href="{{ url()->previous() }}" class="position-absolute mt-3 ms-3">
<img src="/img/back.png" alt="" >
</a>
</div>
</div>
</div>
<div class="container d-flex justify-content-center" style="z-index: -1" >
{{-- <img src="" class="rounded mx-auto d-block position-absolute"style="top: 150px" alt="..."> --}}
</div>
<div class="container d-flex flex-column align-items-center mt-5">
<h1 class="namaMenu">{{$menu->namaMenu}}</h1>
<h3 class="harga" style="color: #F46C49">{{$menu->harga}}</h3>
<div class="container d-flex justify-content-center align-items-center my-3">
<a type="button" class="mx-3 editButton minus"><img src="/img/minus-2.png" alt="" style="width: 37px; height:37px"></a>
<h1 wire:model="quantity" style="width:58px; height:58px; background-color:#fff;" class="mx-3 text-center shadow bg-body rounded quantity" >1</h1>
<a type="button" class="mx-3 editButton plus"><img src="/img/plus-2.png" alt="" style="width: 37px; height:37px"></a>
</div>
</div>
<div class="container shadow p-3 bg-body rounded">
<h5>Add notes <span class="text-muted">(optional)</span></h5>
<div class="form-floating">
<textarea name="note" class="form-control rounded" placeholder="Leave a comment here" id="floatingTextarea2" style="height: 175px"></textarea>
<label for="floatingTextarea2">Notes</label>
</div>
</div>
<form id="quantityForm" action="" method="post" enctype="multipart/form-data">
#csrf
<div class="container my-5">
<button type="submit" class="btn btn-lg text-white text-center form-control" style="background-color: #F46C49">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-cart-plus" viewBox="0 0 16 16">
<path d="M9 5.5a.5.5 0 0 0-1 0V7H6.5a.5.5 0 0 0 0 1H8v1.5a.5.5 0 0 0 1 0V8h1.5a.5.5 0 0 0 0-1H9V5.5z"/>
<path d="M.5 1a.5.5 0 0 0 0 1h1.11l.401 1.607 1.498 7.985A.5.5 0 0 0 4 12h1a2 2 0 1 0 0 4 2 2 0 0 0 0-4h7a2 2 0 1 0 0 4 2 2 0 0 0 0-4h1a.5.5 0 0 0 .491-.408l1.5-8A.5.5 0 0 0 14.5 3H2.89l-.405-1.621A.5.5 0 0 0 2 1H.5zm3.915 10L3.102 4h10.796l-1.313 7h-8.17zM6 14a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm7 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/>
</svg>
<span style="text-center font-size: 1rem">Tambahkan</span>
</button>
</div>
</form>
<script>
$(document).ready(function(e){
$(".plus").click(function(e){
var quantity = $('.quantity').text();
quantity = parseInt(quantity);
quantity++;
$('.quantity').text(quantity);
});
$(".minus").click(function(e){
var quantity = $('.quantity').text();
quantity = parseInt(quantity);
if(quantity > 1){
quantity--;
$('.quantity').text(quantity);
}
});
$("#quantityForm").submit(function(e){
e.preventDefault();
var quantity = $('.quantity').text();
quantity = parseInt(quantity);
var note = $('#floatingTextarea2').val();
var url = "{{route('pesan', [$meja->id, $menu->id])}}";
$.ajax({
url: url,
type: 'POST',
data: {
"_token": "{{ csrf_token() }}",
'id': "{{$menu->id}}",
'namaMenu': "{{$menu->namaMenu}}",
'harga': "{{$menu->harga}}",
'jumlah': quantity,
'note': note
},
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
});
});
</script>
{{-- <script src="/js/detail.js"></script> --}}
#endsection
And this is the error i got
enter image description here
Please, anyone help me :), I really apreciate for your help.
Related
i'm trying to implement this payment,changing the user->pay from a default value of 0 to 1,hoW? pressing the checkbox and changing his value. This will log into videos that can be watched only from that customers. Every time i try to enter the url ( i'm logged already ) it redirects to the home :(
PaymentsController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class PaymentsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
*
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$user = Auth::user();
return view('home',compact('user'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show()
{
return view('sub.payment')->with(Auth::user());
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit(User $User)
{
return view('sub.payment', compact('user'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, User $user)
{
$request->validate([
'pay'=>'required']);
$user->pay = $request->pay;
$user->save();
return redirect()->route('/home')->with('success', 'Congratulazioni per l/abbonamento!');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
web.php
Route::get('/payments', [App\Http\Controllers\PaymentsController::class,'update'])->name('payments.update');
payment.blade.php
#extends('layouts.app')
#section('content')
<div class="container" style="background: rgb(12, 22, 28)">
<div class="card1"style="justify-content:center">
<header class="header">
<h1>ESTREMI PER IL PAGAMENTO</h1>
</header>
<div class="payment">
<div class="card">
<ul class="list-group list-group-flush">
<li class="list-group-item"><h5>IL TUO PIANO</h5></li>
<li class="list-group-item"><p> Paghi 29,99£</p></li>
</ul>
<label for="name" class="label1">{{ __('Nome') }}</label>
<input id="name" type="text" class="input1" name="name" value="{{ Auth::user()->name }}">
<label for="surname" class="label1">{{ __('Descrizione del video') }}</label>
<input id="surname" type="text" class="input1" name="surname" value="{{ Auth::user()->surname }}">
<form method="POST" action="{{ route('payment.update', $user) }}">
<main class="primoInput" style="position:relative;">
#method('PUT') #csrf
<input type="checkbox" id="coding" name="pay" value="1">
<label for="coding">Accetta </label>
<div class="card-body">
<p class="card-text"id="condizioni">
Codice di sicurezza Creando un account accetti che il tuo abbonamento abbia inizio immediatamente e confermi di aver letto e accettato le nostre Condizioni di utilizzo e l'Informativa sulla privacy e sui cookie. Il tuo abbonamento verrà rinnovato automaticamente al costo di 29,99 € e la quota ti sarà addebitata mensilmente tramite il metodo di pagamento da te scelto, fino a quando non deciderai di disdirlo. Puoi disdire in qualsiasi momento, ogni mese, selezionando “Disdici abbonamento” da “Il mio account”.
</p>
<button type="submit" class="buttonBig"> {{ __('ATTIVA ABBONAMENTO') }}</button>
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
I have implemented a notification system in my app and it works fine, but when I want to use it in another controller that uses ajax, the notifications are not loaded in the database. Is there any limitation with Ajax to do this kind of notifications?
Suggestions?
index view:
#extends('layouts.app')
#section('content')
<section class="section">
<div class="section-header">
<h3 class="page__heading">Derivar IP</h3>
</div>
<div class="section-body">
<div class="row">
<div class="col-sm-9">
<div class="card">
<div class="card-header">
<h4>Siniestros para derivar</h4>
</div>
<div class="card-body">
<table class="table table-sm m-1 p-1 table-bordered table-hover table-striped tablita" style="width:100%">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Siniestro</th>
<th scope="col">Fecha IP</th>
<th scope="col">Modalidad</th>
<th scope="col">Dirección</th>
<th scope="col">Localidad</th>
<th scope="col">Inspector</th>
<th scope="col">Acciones</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-sm-3" style="position:fixed; bottom:250px; right:0px">
<div class="card">
<div class="card-header">
<span id="addT">Asignar IP</span>
<span id="updateT">Asignar IP</span>
</div>
<div class="card-body">
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label for="siniestro">Siniestro</label>
<input type="text" name="siniestro" id="siniestro" class="form-control">
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<label for="inspector">inspector</label>
<select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" id="inspector"´for="inspector" name="inspector"">
#foreach ($users as $user)
<option value="{{ $user->id }}">{{ $user->name }}</option>
#endforeach
</select>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label for="patente">Patente</label>
<input type="text" name="patente" id="patente" class="form-control">
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label for="fechaip">Fecha IP</label>
<input type="date" name="fechaip" id="fechaip" class="form-control">
</div>
</div>
<input type="hidden" id="id">
<!-- <button type="button" href="#" data-target="#ModalEnviar" class="btn btn-primary m-2" data-toggle="modal">Enviar IP</button> -->
<button type="submit" id="updateButton" class="btn btn-primary btn-sm" onclick="updateData(event)">Update</button>
</div>
</div>
</div>
</div>
</div>
</section>
#endsection
<!-- DataTables JS -->
<script src="{{ asset('assets/js/jquery.min.js') }}"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/jszip-2.5.0/dt-1.11.5/b-2.2.2/b-colvis-2.2.2/b-html5-2.2.2/b-print-2.2.2/r-2.2.9/datatables.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>
<!-- searchPanes -->
<script src="https://cdn.datatables.net/searchpanes/1.0.1/js/dataTables.searchPanes.min.js"></script>
<!-- select -->
<script src="https://cdn.datatables.net/select/1.3.1/js/dataTables.select.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/js/all.min.js" integrity="sha512-6PM0qYu5KExuNcKt5bURAoT6KCThUmHRewN3zUFNaoI6Di7XJPTMoT6K0nsagZKk2OB4L7E3q1uQKHNHd4stIQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
#section('javas')
<script>
$('.tablita').DataTable({
"processing": "true",
"serverSide": "true",
"ajax": "{{route('datatable.paraderivar')}}",
"select": "true",
"columns":[
{data: 'id'},
{data: 'siniestro'},
{data: 'fechaip'},
{data: 'modalidad'},
{data: 'direccion'},
{data: 'localidad'},
{data: 'inspector'},
]
});
</script>
<script>
$('#addT').hide();
$('#addButton').hide();
$('#updateT').show();
$('#updateButton').show();
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
//---------------------------------------------- Llamar datos de la BD ---------------------------------------------------------------
function allData(){
$.ajax({
type: "GET",
dataType: "json",
url: "/teacher/all",
success: function (response){
var data = ""
$.each(response, function(key, value){
data = data + "<tr>"
data = data + "<td>"+value.id+"</td>"
data = data + "<td>"+value.siniestro+"</td>"
data = data + "<td>"+value.fechaip+"</td>"
data = data + "<td>"+value.modalidad+"</td>"
data = data + "<td>"+value.direccion+"</td>"
data = data + "<td>"+value.localidad+"</td>"
data = data + "<td>"+value.inspector+"</td>"
data = data + "<td>"
data = data + "<button class='btn btn-info btn-sm' onclick='editData("+value.id+")'>Asignar</button>"
data = data + "</td>"
data = data + "</tr>"
})
$('tbody').html(data);
}
})
}
// --------------------------------------------- fin de llamar datos de la DB ----------------------------------------------------------
allData();
// --------------------------------------------- Limpiar los campos despues del submit -------------------------------------------------
function clearData(){
$('#siniestro').val('');
$('#fechaip').val('');
$('#inspector').val('');
$('#nameError').text('');
$('#titleError').text('');
$('#instituteError').text('');
}
// --------------------------------------------- fin de limpiar los campos despues del submit -------------------------------------------------
// --------------------------------------------- Agregar registros a la table de BD -------------------------------------------------
function addData(){
var siniestro = $('#siniestro').val();
var fechaip = $('#fechaip').val();
var inspector = $('#inspector').val();
var fechaip = $('#fechaip').val();
var patente = $('#patente').val();
$.ajax({
type: "POST",
dataType: "Json",
data: {siniestro:siniestro, fechaip:fechaip, inspector:inspector, patente:patente},
url:"/teacher/store/",
success: function(data){
allData();
clearData();
console.log('datos agregados con éxito');
},
error: function(error){
$('#nameError').text(error.responseJSON.errors.name);
$('#titleError').text(error.responseJSON.errors.title);
$('#instituteError').text(error.responseJSON.errors.institute);
}
})
}
// --------------------------------------------- fin de agregar registros a la table de BD -------------------------------------------------
// --------------------------------------------- Editar registros a la table de BD ---------------------------------------------------------
function editData(id){
$.ajax({
type:"get",
dataType:"json",
url:"/teacher/edit/"+id,
success: function(data){
$('#addT').hide();
$('#addButton').hide();
$('#updateT').show();
$('#updateButton').show();
$('#id').val(data.id);
$('#siniestro').val(data.siniestro);
$('#fechaip').val(data.fechaip);
$('#inspector').val(data.inspector);
$('#patente').val(data.patente);
console.log(data);
}
})
}
// --------------------------------------------- Fin de editar registros a la table de BD -------------------------------------------------
// --------------------------------------------- Update de registros a la table de BD -----------------------------------------------------
function updateData(event){
event.preventDefault();
var id = $('#id').val();
var siniestro = $('#siniestro').val();
var fechaip = $('#fechaip').val();
var inspector = $('#inspector').val();
var patente = $('#patente').val();
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
$.ajax({
type: "PUT",
dataType: "json",
data: {inspector:inspector, siniestro:siniestro, fechaip:fechaip, patente:patente},
url: "/teacher/update/"+id,
success: function(response){
allData();
clearData();
console.log('Siniestro asignado con éxito');
}
})
}
</script>
#endsection
Controller:
<?php
namespace App\Http\Controllers;
use App\Models\Teacher;
use App\Models\Siniestro;
use App\Models\User;
//Notificaciones
use App\Notifications\DataEstadoNotificacion;
use App\Events\DataEstadoEvent;
use Illuminate\Support\Facades\Notification;
use Illuminate\Http\Request;
class TeacherController extends Controller
{
public function allUser(){
$data = User::orderBy('fechaip','DESC')->get();
dd($data);
return response()->json($data);
}
//-----------storeData------------
public function storeData(Request $request){
$request->validate([
]);
$data = Siniestro::insert($request->all()
);
return response()->json($data);
}
// public function editData($id){
// $data = Siniestro::findOrFail($id);
// return response()->json($data);
// }
public function updateData(Request $request, $id)
{
$data = Siniestro::findOrFail($id)->update($request->all();
// event(new DataEstadoEvent($data));
);
return response()->json($data);
auth()->user()->notify(new DataEstadoNotification($data));
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
}
}
Notification:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\Models\Siniestro;
use Carbon\Carbon;
class DataEstadoNotificacion extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(Data $data)
{
$this->data = $data;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'siniestro' => $this->data->siniestro,
'patente' => $this->data->patente,
'fechaip' => $this->data->fechaip,
'tiempo' => Carbon::now()->diffForHumans(),
];
}
}
EventServiceProvider
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use App\Events\SiniestroEstadoEvent;
use App\Listeners\SiniestroEstadoListener;
use App\Events\DataEstadoEvent;
use App\Listeners\DataEstadoListener;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
SiniestroEstadoEvent::class => [
SiniestroEstadoListener::class,
],
DataEstadoEvent::class => [
DataEstadoListener::class,
],
];
/**
* Register any events for your application.
*
* #return void
*/
public function boot()
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*
* #return bool
*/
public function shouldDiscoverEvents()
{
return false;
}
}
Listener:
<?php
namespace App\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Notification;
use App\Models\User;
use App\Notifications\DataEstadoNotificacion;
class DataEstadoListener
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param object $event
* #return void
*/
public function handle($event)
{
$users = User::find($event->data->inspector);
Notification::send($users, new DataEstadoNotificacion($event->data));
}
}
Event:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class DataEstadoEvent
{
public $data;
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
When I click the search button, this shows.
error image
It shows Error Exception for (Cannot use object of type Illuminate\Database\MySqlConnection as array )
<div class='container'>
<div class="row" >
<div class="col-md-12">
<br />
<h3 align="center">Data Pesakit</h3>
<br />
#if($message = Session::get('success'))
<div class="alert alert-success">
<p>{{$message}}</p>
</div>
#endif
<div align="right">
Add
<br />
<br />
</div>
<div class="col-md-12">
<form action="/search" method="get" class="d-none d-md-inline-block form-inline ml-auto mr-0 mr-md-3 my-2 my-md-0">
<div class="form-group">
<input class="form-control" type="search" name="search" />
<span class="form-group-btn">
<button class="btn btn-primary" type="submit">Search</button>
</span>
</div>
</form>
</div>
<table class="table table-bordered">
<tr>
<th>Nama Pertama</th>
<th>Nama Akhir</th>
<th>Kad Pengenalan</th>
<th>No Telefon</th>
<th>Alamat Rumah</th>
<th>Alamat Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach($pesakit as $row)
<tr>
<td>{{$row['namaPertama']}}</td>
<td>{{$row['namaAkhir']}}</td>
<td>{{$row['kadPengenalan']}}</td>
<td>{{$row['noTelefon']}}</td>
<td>{{$row['alamatRumah']}}</td>
<td>{{$row['email']}}</td>
<td>Edit</td>
<td><form method="post" class="delete_form" action="{{action('PesakitController#destroy',$row['id'])}}">
{{csrf_field()}}
<input type="hidden" name="_method" value="DELETE" />
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('.delete_form').on('submit', function(){
if(confirm("Are you sure you want to delete it?"))
{
return true;
}
else
{
return false;
}
});
});
</script>
#endsection
This is code for views
class PesakitController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$pesakit = Pesakit::all()->toArray();
return view('pesakit.index', compact('pesakit'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('pesakit.create');
}
public function search(Request $request)
{
$search = $request->get('search');
$pesakit = DB::table('pesakit')
->where('namaPertama', 'like', '%'.$search. '%');
return view('pesakit.index', ['pesakit'=>$pesakit]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'namaPertama' => 'required',
'namaAkhir' => 'required',
'kadPengenalan' => 'required',
'noTelefon' => 'required',
'alamatRumah' => 'required',
'email' => 'required'
]);
$pesakit = new Pesakit([
'namaPertama' => $request->get('namaPertama'),
'namaAkhir' => $request->get('namaAkhir'),
'kadPengenalan' => $request->get('kadPengenalan'),
'noTelefon' => $request->get('noTelefon'),
'alamatRumah' => $request->get('alamatRumah'),
'email' => $request->get('email')
]);
$pesakit->save();
return redirect()->route('pesakit.create')->with('success',
'Data Berjaya Disimpan');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$pesakit = Pesakit::find($id);
return view('pesakit.edit', compact('pesakit', 'id'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'noTelefon' => 'required',
'alamatRumah' => 'required'
]);
$pesakit = Pesakit::find($id);
$pesakit->noTelefon = $request->get('noTelefon');
$pesakit->alamatRumah = $request->get('alamatRumah');
$pesakit->save();
return redirect()->route('pesakit.index')->with('success', 'Data Dikemas kini');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$pesakit = Pesakit::find($id);
$pesakit->delete();
return redirect()->route('pesakit.index')->with('success', 'Data Deleted');
}
}
This is the controller
Route::get('/', function () {
return view('utama');
});
Route::resource('pesakit', 'PesakitController');
Route::resource('petugas', 'PetugasController');
Route::resource('pendaftaran', 'PendaftaranController');
Route::get('/search','PesakitController#search');
This is the Route
I try to look for simple error such as ; or misspell or something but i cannot find it. It says some array problem but does not all crud is array??
add get()
public function search(Request $request)
{
$search = $request->get('search');
$pesakit = DB::table('pesakit')
->where('namaPertama', 'like', '%'.$search. '%')->get();
return view('pesakit.index', ['pesakit'=>$pesakit]);
}
I want to export data from the database to .xlsx using Laravel-Excel.
I want to pass three parameters to query the data and download into excel file.
I already search and read a few examples but still failed to make the excel file to download.
This is my blade file.
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="card">
<div class="card-header">Download Report</div>
<div class="card-body">
<div class="col-md-12" style="margin-bottom:15px">
<select class="form-control" name="plant" id="plant">
<option selected value="All">Please Select Plant</option>
#foreach($plants as $plant)
<option value="{{ $plant->id }}">{{ $plant->name }}</option>
#endforeach
</select>
</div>
<div class="col-md-12" style="">
<div class="input-group input-daterange" align="center">
<input type="text" name="from_date" id="from_date" readonly class="form-control" value="<?php echo date("Y-m-d");?>" />
<div class="input-group-addon" >To</div>
<input type="text" name="to_date" id="to_date" readonly class="form-control" value="<?php echo date("Y-m-d");?>"/>
</div>
</div>
<br>
<div class="col-md-12" align="center">
<button type="button" name="search" id="search" class="btn btn-info btn-block">Download</button>
</div>
</div>
</div>
</div>
<div class="col-md-3"></div>
</div>
</div>
<script type="text/javascript">
$(function() {
var date = new Date();
$('.input-daterange').datepicker({
todayBtn: 'linked',
format: 'yyyy-mm-dd',
autoclose: true
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#search').click(function(e){
e.preventDefault();
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
var plant = $('#plant').val();
if(plant != 'All')
{
$.ajax({
url:"{{ route('export') }}",
data:{from_date:from_date, to_date:to_date, plant:plant},
dataType:"json",
})
}
else
{
alert('Please Select Plant');
}
});
});
</script>
#endsection
This is my function at the controller
public function export(Request $request)
{
return (new DetailReportDownload($request->plant,$request->from_date,$request->to_date))->download('Report Details.xlsx');
}
and This is my Export file
class DetailReportDownload implements FromQuery, WithHeadings
{
use Exportable;
protected $plant,$from,$to;
public function __construct(String $from,String $to,String $plant)
{
$this->plant = $plant;
$this->from = $from;
$this->to = $to;
}
public function headings(): array
{
return [
'plandate',
'workcentre',
'partno',
'prodduration',
'totaldowntime',
'planout',
'cumout',
];
}
public function query()
{
return DB::table('plannings')
->select(DB::raw('plandate, workcentre, partno, prodduration, coalesce(sum(downduration),0) as totaldowntime, planout, cumout'))
->join('prodstatuses', 'plannings.id', '=', 'prodstatuses.id')
->leftJoin('downtimes', 'plannings.id', '=', 'downtimes.plan_id')
->whereBetween('plandate', array($this->from, $this->to))
->where('plant_id',$this->plant)
->where('status','Finished')
->groupBy('plannings.id')
->orderBy('plannings.id');
}
}
I wanted to download excel file from parameter given in blade file.
Thanks in advance for any help
create a provider to add below code & register to app.php file
Sheet::macro('styleCells', function (Sheet $sheet, string $cellRange, array $style) {
$sheet->getDelegate()->getStyle($cellRange)->applyFromArray($style);
});
And create class to download data using parameters,
<?php
namespace App\Modules\User\Http\Exports;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
/**
* Class ExportUsers
* #package App\Exports
*/
class ExportUsers implements FromView, ShouldAutoSize, WithEvents
{
protected $plannings;
/**
* ExportUsers constructor.
* #param Collection $plannings
*/
public function __construct(Collection $plannings) {
$this->plannings = $plannings;
}
/**
* #return View
*/
public function view() : View {
return view('plannings_list', [
'plannings' => $this->plannings,
]);
}
/**
* #return array
*/
public function registerEvents() : array {
return [
AfterSheet::class => function (AfterSheet $event) {
$this->createStyle($event, 'A1:N1', 9);
$event->sheet->styleCells(
'A1:N1',
[
'font' => [
'bold' => true,
]
]
);
},
];
}
/**
* #param $event
* #param $cell
* #param $size
* #throws \PhpOffice\PhpSpreadsheet\Exception
*/
private function createStyle($event, $cell, $size) {
/** #var AfterSheet $event */
$event->sheet->getDelegate()->getStyle($cell)->getFont()->setSize($size);
}
}
add this code to controller
private function downloadCsv($exportCsvList) {
return Excel::download(new ExportUsers($exportCsvList),
'students.xlsx');
}
I have a previous form in which i created a user and technician. the data is well filled in the tables of the database. Now the form redirects me to another form in which the technician id is needed. I'm working to make the technician id in the new form auto filled from the previous form. I hope my question is clear and I which you could help me. I put my code and the form I want to be auto-filled.Hope you could help me.
Model1
public function tarificationtache()
{
return $this->belongsToMany('App\tarificationtache','technicien_tarificationtache','technicien_id','tarificationtache_id');
}
Model2
public function techniciens()
{
return $this->belongsToMany('App\technicien','technicien_tarificationtache','tarificationtache_id','technicien_id');
}
technicien.Controller
public function store(Request $request)
{
$user = new user();
$user->nom = $request->input('nom');
$user->prenom = $request->input('prenom');
$user->tel = $request->input('tel');
$user->mobil = $request->input('mobil');
$user->role = $request->input('role');
$user->email = $request->input('email');
$user->password = $request->input('password');
$user->save();
$technicien = new technicien();
$technicien->user_id = $user->id;
$technicien->actif = $request->input('actif');
$technicien->moyenne_avis = $request->input('moyenne_avis');
$technicien->save();
$technicien->zoneintervention()->attach($request->zoneintervention_id);
$technicien->metier()->attach($request->metier_id);
return redirect('tarification/create');
}
tarification.controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\tarificationtache;
use App\technicien;
use App\tache;
class TarificationController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$Listtache=tache::orderBy('libelle_tache')->get();
$Listtarification=tarificationtache::all();
return view('tarification.index',
['tarification'=>$Listtarification]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$techniciens = technicien::orderBy('id','desc')->get();
$taches = Tache::orderBy('id', 'desc')->get();
return view('tarification.create')->with('taches', $taches)->with('techniciens', $techniciens);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$tarification = new tarificationtache();
$tarification ->tache_id = $request->input('tache_id');
$tarification ->Tarif =$request->input('Tarif');
$tarification->save();
$tarification->techniciens()->attach($request->technicien_id);
return redirect('tarification');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$tache=Tache::find($id);
return view('tache.edit',['libelle_tache'=>$tache],
['Tarif'=>$tache],['metier_id'=>$tache]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$tache =Tache::find($id);
$tache->delete();
return redirect('tache');
}
}
View
#extends('Layouts/app')
#section('content')
#if(count($errors))
<div class="alert alert-danger" role="alert">
<ul>
#foreach($errors ->all() as $message)
<li>{{$message}}</li>
#endforeach
</ul>
</div>
#endif
<div class="container">
<div class="row"></div>
<div class="col-md-12">
<form action=" {{url ('tarification') }}" method="post">
{{csrf_field()}}
<div class="form-group">
<label for="technicien">Technicien</label>
<select name="technicien_id" id="technicien" class="form-control" >
#foreach($techniciens as $techniciens)
<option value="{{ $techniciens->id }}">
{{$techniciens->id}}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="Tache">Libelle Tache</label>
<select name="tache_id" id="Tache" class="form-control">
#foreach($taches as $tache)
<option value="{{ $tache->id }}">
{{$tache->libelle_tache}}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">Tarif</label>
<input type="text" name ="Tarif" class="form-control"value="{{old('tarif')}}">
</div>
<div class="form-group">
<input type="submit" value = "enregistrer" class="form-control btn btn-primary">
</div>
</form>
</div>
</div>
<script>
#endsection
technicien.controller
public function store(Request $request)
{
$user = new user();
$user->nom = $request->input('nom');
$user->prenom = $request->input('prenom');
$user->tel = $request->input('tel');
$user->mobil = $request->input('mobil');
$user->role = $request->input('role');
$user->email = $request->input('email');
$user->password = $request->input('password');
$user->save();
$technicien = new technicien();
$technicien->user_id = $user->id;
$technicien->actif = $request->input('actif');
$technicien->moyenne_avis = $request->input('moyenne_avis');
$technicien->save();
$technicien->zoneintervention()->attach($request->zoneintervention_id);
$technicien_id = $technicien->id;
return redirect('tarification/create')->with(‘technicien_id’, $technicien_id);
}
tarification.view
<div class="form-group">
<label for="technicien">Technicien</label>
<select name="technicien_id" id="technicien"
class="form-control" >
#foreach($techniciens as $techniciens)
<option value="{{ $techniciens->id }}">
{{ $technicien_id }}
</option>
#endforeach
</select>
</div>
here is my new code i did exactly as you told me
You have to pass that value to the view.
$technician_id = $user->id;
return view(‘tarification/create’)->with(‘technician_id’, $technician_id);
Now you can use this value in your view.
<div class="form-group">
<label for="technicien">Technicien</label>
<input type="text" value={{$technician_id}} >
</div>