Am new to laravel and found it very difficult to devise a code for uploading CSV file to MySQL...I have done the following coding...
Controller:
public function index()
{
return view('items.items');
}
public function import(Request $request)
{
if($request->file('imported-file'))
{
$path = $request->file('imported-file')->getRealPath();
$data = Excel::load($path, function($reader) {})->get();
if(!empty($data) && $data->count())
{
$data = $data->toArray();
for($i=0;$i<count($data);$i++)
{
$dataImported[] = $data[$i];
}
}
Inventory::insert($dataImported);
}
return back();
}
In View:
<form action="{{route('items.import')}}" method="post" enctype="multipart/form-data">
<div class="col-md-6">
{{csrf_field()}}
<input type="file" name="imported-file"/>
</div>
<div class="col-md-6">
<button class="btn btn-primary" type="submit">Import</button>
</div>
</form>
In Routes.php
Route::get('items', 'ItemController#index');
Route::post('items/import',[ 'uses' => 'ItemController#import', 'as'
=> 'items.import'] );
This gives me an error called NotFoundHttpException in RouteCollection.php
All what I can understand that there is some method or controller is missing in my code but could not figured out what is that...can anyone please help me here I am really got stuck into this for quiet a long time.
First try using
Route::get('items/import',[ 'uses' => 'ItemController#import', 'as' => 'items.import'] );
if the items/import is accessed then
Route::any('items/import',[ 'uses' => 'ItemController#import', 'as' => 'items.import'] );
Other than this you might want to use:
<form action="/items/import" method="post" and keep the post in route
instead of
<form action="{{route('items.import')}}" method="post"
You need to define just simple route
Route::any('items/import',ItemController#import);
and make sure that you have to add a dependency in the controller. is it there? Like:
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
run those command and then refres page
1.php artisan route:clear
2.php artisan cache:clear
3.composer dumpautoload
and last one is
4.composer update
You should try this your form like:
<form action="{{ url('items/import') }}" method="POST" enctype="multipart/form-data">
And your import function like:
use Redirect;
public function import(Request $request)
{
if($request->file('imported-file'))
{
$path = $request->file('imported-file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count())
{
$data = $data->toArray();
for($i=0;$i<count($data);$i++)
{
$dataImported[] = $data[$i];
}
}
Inventory::insert($dataImported);
}
return redirect()->route('items.import');
}
Updated answer
Route::get('items', 'ItemController#index')->name('items');
Route::post('items/import', 'ItemController#import')->name('items.import');
public function import(Request $request)
{
if($request->file('imported-file'))
{
$path = $request->file('imported-file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count())
{
$data = $data->toArray();
for($i=0;$i<count($data);$i++)
{
$dataImported[] = $data[$i];
}
}
Inventory::insert($dataImported);
}
return redirect()->route('items.import');
}
Related
I'm trying to create a CMS project but I got this error when I create the URL & Controller for the edit button (Call to undefined method App\Models\Catogry::firstItem()).
here is the web.php page
<?php
use App\Http\Controllers\CategoryController;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
// $users = User::all();
$users = DB::table('users')->get();
return view('dashboard', compact('users'));
})->name('dashboard');
//category controller
Route::get('/category/all', [CategoryController::class, 'index'])->name('index.category');
Route::post('/category/add', [CategoryController::class, 'store'])->name('store.category');
Route::get('/category/edit/{id}', [CategoryController::class, 'edit']);
here Is the CategoryController >>
<?php
namespace App\Http\Controllers;
use App\Models\Catogry;
use Carbon\Carbon;
use Illuminate\Auth\Events\Validated;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class CategoryController extends Controller
{
public function index()
{
$categories = Catogry::latest()->paginate(5);
return response()->view('Admin.category.index', compact('categories'));
}
public function store(Request $request)
{
$validated = $request->validate([
'category_name' => 'required|unique:catogries|max:25|min:4',
]);
//insert with three ways *****
// Catogry::insert([
// 'category_name' => $request->category_name,
// // 'user_id' => Auth::user()->id,
// 'created_at' => Carbon::now()
// ]);
$categories = new Catogry;
$categories->category_name = $request->category_name;
$categories->user_id = Auth::user()->id;
$categories->save();
// $date = array();
// $data['category_name'] = $request->category_name;
// $data['user_id'] = Auth::user()->id;
// DB::table('catogries')->insert($data);
return redirect()->back()->with('success', 'Category Inserted Successfully');
}
public function Edit($id)
{
// return 'edit page';
$categories = Catogry::findOrFail($id);
return response()->view('Admin.category.edit', compact('categories'));
}
}
here is the edit.blade.php page >>
<form action=" " method="POST">
#csrf
<div class="card-body">
<div class="form-group">
<label for="category_name">Edit Your Category Name</label>
<input type="text" class="form-control" id="category_name" name="category_name" placeholder="Enter category name"
value="{{ $categories->category_name }}">
</div>
<div class="card-footer">
<button type="submit" class="btn btn-info">Update Category</button><br>
#error('category_name')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
<!-- /.card-footer -->
</form>
Laravel Excel to export data will download empty data with only headers in excel sheet! I want to export only the filtered data from my search using excel but it will download an empty excel sheet only with headers!! please can anyone tell me where is my error!
DealerExportSearch.php
class DealersSearchExport implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
{
use Exportable;
protected $name;
protected $email;
protected $mobile_no;
protected $city;
public function __construct( $name, $email, $mobile_no , $city)
{
$this->name = $name;
$this->email = $email;
$this->mobile_no = $mobile_no;
$this->city = $city;
}
//function select data from database
public function collection()
{
return Dealer::select()->where('name', $this->name)
->where('email', $this->email)
->where('mobile_no', $this->mobile_no)
->where('city', '=', $this->city) //i tried using the above and this also same result
->get();
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
$cellRange = 'A1:W1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(12);
},
];
}
//function header in excel
public function headings(): array
{
return [
'No',
'name',
'email',
'mobile_no',
'shop_name',
'city',
'address'
];
}
}
my controller
public function index(Request $request)
{
$method = $request->method();
if ($request->isMethod('get')) {
$name = $request->name;
$email = $request->email;
$city = $request->city;
$mobile_no = $request->mobile_no;
if ($request->has('search')) {
$dealers = Dealer::where('name', 'LIKE', '%'.$name.'%')
->where('email', 'LIKE', '%'.$email.'%')
->where('mobile_no', 'LIKE', '%'.$mobile_no.'%')
->where('city', 'LIKE', '%'.$city.'%')
->paginate(5);
return view('dealer.index', compact('dealers'));
}
elseif ($request->has('exportSearchExcel')) {
return Excel::download(new DealersSearchExport($name ?? '', $email ?? '', $mobile_no ?? '', $city ?? ''), 'DealersSearchExcel-reports.xlsx');
}
else{
$dealers = Dealer::orderBy('id', 'DESC')->paginate(5);
return view('dealer.index', compact('dealers'));
}
}
}
blade
<form action="{{ route('dealer.index') }}" method="GET" enctype="multipart/form-data">
#csrf
<div class="form-group row">
<div class="col-sm-3">
<label for="name">Name: </label>
<input class="form-control" name="name" value="{{ request()->input('name') }}" type="text" placeholder="The Dealer Name">
</div>
.....................................................................
</div>
<div class="col-md-12 pt-3 text-right">
<button type="submit" name="search" class="btn btn-primary"><i class="fa fa-fw fa-search"></i> Search</button>
<button type="submit" name="exportSearchExcel" class="btn btn-secondary text-light"><i class="fa fa-download"></i> Export Excel </button>
</div>
</div>
No error is showing just in my console it will return this error and download an empty xslx whenever I press the export button.
Resource interpreted as Document but transferred with MIME type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet: "http://127.0.0.1:8000/dealer?_token=TTlpqFNn4hr5rwI1jSlt0d4mbtww2moO8i1WWjfn&name=&email=&mobile_no=&exportSearchExcel=".
Update
I fixed it by changing my query in DealerExportSearch.php to the same query that I have in controller then it worked
DealerExportSearch.php
class DealersSearchExport implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents , WithMapping
{
//the above codes not changed till the collection function
//function select data from database
public function Collection()
{
return Dealer::where('name', 'LIKE', '%'.$this->name.'%')
->where('email', 'LIKE', '%'.$this->email.'%')
->where('mobile_no', 'LIKE', '%'.$this->mobile_no.'%')
->where('city', 'LIKE', '%'.$this->city.'%')
->get();
}
public function map($row): array{
$fields = [
$row->id,
$row->name,
$row->gender,
$row->date_of_birth,
$row->email,
$row->mobile_no,
$row->shop_name,
$row->city,
$row->address,
];
return $fields;
}
///below codes not changed .....
I am trying to upload image to database using Ajax but It store image into public/images directory only,never store image into database,I had grabbed from itsolution for test purpose but never work,Could any one tell where am I wrong?
Route
Route::get('ajaxImageUpload', ['uses'=>'AjaxImageUploadController#ajaxImageUpload']);
Route::post('ajaxImageUpload', ['as'=>'ajaxImageUpload','uses'=>'AjaxImageUploadController#ajaxImageUploadPost']);
Controller
public function ajaxImageUploadPost(Request $request) {
$validator = Validator::make($request->all(), [
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if ($validator->passes()) {
$input = $request->all();
$input['image'] = time() . '.' . $request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $input['image']);
AjaxImage::create($input);
return response()->json(['success' => 'done']);
}
return response()->json(['error' => $validator->errors()->all()]);
}
View
<form action="{{ route('ajaxImageUpload') }}" enctype="multipart/form-data" method="POST">
<input type="text" name="title" class="form-control" placeholder="Add Title">
<input type="file" name="image" class="form-control">
<button class="btn btn-success upload-image" type="submit">Upload Image</button>
</form>
<script>
$("body").on("click", ".upload-image", function (e) {
$(this).parents("form").ajaxForm(options);
});
var options = {
complete: function (response) {
if ($.isEmptyObject(response.responseJSON.error)) {
$("input[name='title']").val('');
alert('Image Upload Successfully.');
} else {
printErrorMsg(response.responseJSON.error);
}
}};
function printErrorMsg(msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display', 'block');
$.each(msg, function (key, value) {
$(".print-error-msg").find("ul").append('<li>' + value + '</li>');
});
}
</script>
Save Image Location To The Database
use intervention;
public function ajaxImageUploadPost(Request $request){
$validator = Validator::make($request->all(), ['title' => 'required','image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
if ($validator->passes()) {
$image = new AjaxImage();
$image->title = $request->title;
if ($request->hasFile('image')) {
$img=$request->file('resim');
$filename=time().".".$img->getClientOriginalExtension();
$location=public_path('img/'.$filename);
Image::make($img)->save($location);
$image->image=$filename;
}
$image->save();
return response()->json(['success'=>'done']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
So I am working on a laravel project and I want that if a user types in their order code, the order will show up with the details. For some reason, the order code doesn't get through the if statement, because I get the output 'Order not found.' all the time, even if I type in an order code that is present in my orders table.
TrackController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Order;
class TrackController extends Controller
{
public function index()
{
return view ('track.index');
}
public function show($id)
{
$order = Order::where('code', $id)->first();
return view('track.show',[
'order' => $order
]);
}
public function redirect(Request $request)
{
$orderCode = $request->input('order-track-id');
$order = Order::where('code', $orderCode)->first();
if(!$order){
return redirect('/track')->with('error', 'Order not found.');
}else{
return redirect('/track/' . $order->code);
}
}
}
web.php
Route::get('/track', 'TrackController#index');
Route::post('/track/redirect', 'TrackController#redirect');
Route::get('/track/{id}', 'TrackController#show');
track.index
#extends('layouts/app')
#section('content')
<div class="container">
<div class="row justify-content center">
{!! Form::open(['action' => 'TrackController#redirect', 'method' => 'post']) !!}
{!! csrf_field() !!}
<input type="number" name="input-order-track-id" id="order-track-id">
{{ Form::button('Track', ['type' => 'submit', 'class' => 'btn btn-primary'] ) }}
{!! Form::close() !!}
</div>
</div>
#endsection
What am I doing wrong and why isn't my function putting me through to the show function in the TrackController?
In your redirect controller function.
public function redirect(Request $request)
{
$orderCode = $request->input('input-order-track-id');
$orders = Order::where('code', $orderCode)->get();
if($orders->isEmpty()){
return redirect('/track')->with('error', 'Order not found.');
}else{
$order = Order::where('code', $orderCode)->first();
return redirect('/track/' . $order->code);
}
}
I can't figure out what's wrong with my create view. I need the submit button to redirect me to my show view so I can see all the created tags.
Here are the routes to create a tag, to show the tag and then store the tag:
Route::get('/tags/create', ['uses' => 'TagController#create', 'as' => 'tags.create']); // Allows you to create a new tag
Route::post('/postTags', ['uses' => 'TagController#store', 'as' => 'postTags']); // Place where all the tags are stored
Route::get('/tag/show', ['uses' => 'TagController#show', 'as' => 'tags.show']); // Shows you all the existing tags
Here is my tag controller:
public function create()
{
$tag = new Tag();
return view('tags.create', compact('tag'));
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
$tag = new Tag;
$tag->name = $request['name'];
$tag->save();
return redirect()->route("tags.show");
}
public function show()
{
$tags = Tag::all();
return view('tags.show', compact('tags'));
}
And my create view:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>New Tag</h1>
<form method="POST" action="{{route("postTags")}}">
{{csrf_field()}}
<label for="name">Click here to edit the title of your post!</label>
<input type="text" name="Name" id="name" required/>
<input type="submit" value="Submit" onclick="window.location='{{ route("tags.show") }}'"/>
</form>
</body>
</html>
here is the mistake, you given name="Name", the first letter is capital, and in function all are small
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
$tag = new Tag;
$tag->name = $request['name'];
$tag->save();
return redirect()->route("tags.show");
}
also you are creating object in the above function without calling the constructor $tag = new Tag;, create it as $tag = new Tag();