I found the code form this website http://itsolutionstuff.com/post/laravel-56-import-export-to-excel-and-csv-exampleexample.html
This is my route after editing:
Route::post('barang', 'BarangController#importExcel')->name('barang');
This is their Controller, and I just Adding on foreach :
public function importExcel(Request $request)
{
$request->validate([
'import_file' => 'required'
]);
$path = $request->file('import_file')->getRealPath();
$data = Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = [
'kode_barang' => $value->kode_barang,
'nama_barang' => $value->nama_barang,
'kategori_id' => $value->kategori_id,
'jumlah_barang' => $value->jumlah_barang,
'harga_satuan' => $value->harga_satuan,
'tanggal_inputan' => $value->tanggal_inputan,
'deskripsi' => $value->deskripsi,
'status' => $value->status,
];
}
if(!empty($arr)){
Item::insert($arr);
}
}
return back()->with('success', 'Insert Record successfully.');
}
And I Just Adding this on my View :
<form action="{{ route('barang') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
#csrf
#if ($errors->any())
<div class="alert alert-danger">
×
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if (Session::has('success'))
<div class="alert alert-success">
×
<p>{{ Session::get('success') }}</p>
</div>
#endif
<input type="file" name="import_file" />
<button class="btn btn-primary">Import File</button>
</form>
The result show data has insert successfully, but nothing data has insert to my table.
Here my excel CSV format :
R4B6,MONITOR LENOVO,ELEKTRONIK,1,-,10/4/2018,-,Aktif
So, how to make the code right for insert into DB ?
Related
Im a laravel beginner, also my first time to use a framework i just learned laravel for 5 days,so i don't understand much about this framework, im using the latest laravel 8 i have a problem with my project, when trying to validate the data from the form.
i dont know this method is working or not (Probably not)
$request->validate([
'name' => 'required',
'icons' => 'required',
]);
when i trying to get the error message {{$error}} , only showing [] in my view.
<form action="{{ route('poseicon.store') }}" method="post" enctype="multipart/form-data">
#csrf
<div class="display">
<label>name:</label>
<input type="text" name="name" id="name">
<label>icons:</label>
<input type="file" name="icons" id="icons" class="">
{{$errors}}
<input type="submit" value="submit">
</div>
</form>
this is my controller
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'icons' => 'required',
]);
//this working correctly when validate method above deleted
$file = $request->file('icons');
$filename = 'pose-photo-' . time() . '.' . $file->getClientOriginalExtension();
$path = $file->storeAs('img', $filename);
//this also working correctly when validate method above deleted
Poseicon::create([
'name' => $request->name,
'icons' => $filename
]);
return redirect('/poseicon');
}
i already try all the documentation said but still not working
As laravel doc says, you should use one of #error directive or loop over $errors
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
OR
#error('title')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
Simply put this code where you want to show error message. Laravel provide this error code.
In your view page you put this.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
In your controller You simply declare which field required.
$request->validate([
'name' => 'required',
'icons' => 'required',
]);
Try this.
controller
use Illuminate\Support\Facades\Validator;
$validatedData = Validator::make($request->all(), [
'name' => 'required',
'icons' => 'required',
])->validate();
$name = $validatedData['name'];
$icons = $validatedData['icons'];
blade file put this above your form
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
I have a problem with showing error messages or session messages in laravel.
Comment the bootstrap cdn, but makes no differences.
have code like this, works correctly, refreshing the view, but not displaying errors:
Controller.php
return redirect()->route('trainers.show',[$trainer])->with('status','Entrenador actualizado correctamente');
blade.php
#if (session('status'))
<div class="alert alert-success">
{{session('status')}}
</div>
#endif
Controller.php
$validatedData = $request->validate([
'name' => 'required|max: 10',
'avatar' => 'required|image',
'slug' => 'required',
'description' => 'required',
]);
blade.php
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
</div>
#endif
Regarding the session status, you can use \Session::has('status') and \Session::get('status'), like so:
#if(\Session::has('status'))
<div class="alert alert-success">
{{ \Session::get('status') }}
</div>
#endif
And on your errors, you can also use has(), like so:
#if ($errors->has())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error}}</li>
#endforeach
</ul>
</div>
#endif
I'd like to know why my bootstrap success message that's coming from controller (PostsController.php) won't appear in the view (messages.blade.php)?
I see the Bootsrap success green banner coming about but not the message itself. What could be the reason why?
Here's messages.blade.php:
#if(count($errors) > 0)
#foreach($errors->all() as $error)
<div class="alert alert-danger">
{{$error}}
</div>
#endforeach
#endif
#if(session('success'))
<div class="alert alert-success">
{{session('session')}}
</div>
#endif
#if(session('error'))
<div class="alert alert-danger">
{{session('error')}}
</div>
#endif
Here's PostController.php:
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required'
]);
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
return redirect('/posts')->with('success', 'Post Created');
}
#if(session('success'))
...
{{session('session')}}
...
#endif
I think you want session('success') inside the div?
I get no message error after click on submit. Here is my view, which is shown correctly.
{!! Form::open(array('route'=>'store.invitation')) !!}
<div class="form-group">
<input type="hidden" name="iduser" value="{{ $user->id }} "/>
<select class="form-control" name="idgroup">
#foreach ($groups as $group)
<option value="{{ $group->id }}">{{ $group->name }}</option>
#endforeach
</select>
{{ csrf_field() }}
</div>
<div>
{{Form::submit('User einladen',['class' => 'btn btn-primary'])}}
</div>
{!! Form::close() !!}
This is my routes. The last one belongs to this view store.invitation.
Route::get('invitation', 'UsernameController#search')->name('search.username');
Route::post('invitation/result', 'UsernameController#result')->name('result.username');
Route::post('invitation/store', 'InvitationController#store')->name('store.invitation');
And this is my function...
public function store(Request $request)
{
$request->validate([
'idgroup' => [
'required', 'numeric', new AdminGroupRequest, new MaxInvitationAdmin
],
'iduser' => [
'required', 'numeric', new AlreadyInvitation, new AlreadyPartOfGroup, new MaxInvitationUser
]
]);
$iduser = $request->iduser;
$idgroup = $request->idgroup;
$i = new Invitation;
$i->idgroup = $idgroup;
$i->iduser = $iduser;
$i->active = 1;
$i->save();
$username = User::where('id', $iduser)->select('name')->first();
$groupname = Group::where('id', $idgroup)->select('name')->first();
return redirect()->action(
'UsernameController#search')->with('success', 'Sie haben den User ' .$username->name. ' in die Gruppe ' .$groupname->name. ' eingeladen.');
}
EDIT: Problem is the validation. But in my view I have
#if(#count(errors > 0))
#foreach($errors->all() as $error)
<div class="alert alert-danger">
{{$error}}
</div>
#endforeach
#endif
Instead of:
#if(#count(errors > 0))
#foreach($errors->all() as $error)
<div class="alert alert-danger">
{{$error}}
</div>
#endforeach
#endif
you should use
#if($errors->any())
#foreach($errors->all() as $error)
<div class="alert alert-danger">
{{$error}}
</div>
#endforeach
#endif
or because you don't wrap errors in any container you could just use:
#foreach($errors->all() as $error)
<div class="alert alert-danger">
{{$error}}
</div>
#endforeach
Yesterday I started with Laravel, currently busy with my first project, a simple news page.
Unfortunately, I've met some problems while validating my post request, I've tried to search on Google for my issue. And I tried to use those fixes, but strange enough I had no result.
The problem is:
When I post data the normal 'form page' will be shown without any errors. I'm aware that I have double error outputs, it's just for the test.
What do I want to reach?
I want that the validation error will be shown
routes.php
<?php
Route::group(['middleware' => ['web']], function() {
Route::get('/', function() {
return redirect()->route('home');
});
Route::get('/home', [
'as' => 'home',
'uses' => 'HomeController#home',
]);
Route::get('/add_article', [
'as' => 'add_article',
'uses' => 'HomeController#add_article',
]);
Route::post('/add_article', [
'as' => 'add_article.newarticle',
'uses' => 'HomeController#post_article',
]);
});
HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\News;
class HomeController extends Controller
{
public function home(News $news)
{
$articles = $news->orderBy('id','desc')->take(3)->get();
return view('home.home')->with('articles', $articles);
}
public function add_article()
{
return view('home.add_article');
}
public function post_article(Request $request)
{
$this->validate($request, [
'title' => 'required|max:64',
'content' => 'required|max:2048',
]);
// $newNews = new News;
// $newNews->title = $request->title;
// $newNews->content = $request->content;
// $newNews->save();
}
}
add_article.blade.php
#extends('templates.default')
#section('content')
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-6 col-xl-6 offset-md-3 offset-lg-3 offset-xl-3">
<p class="lead">New news article</p>
<div class="card">
<div class="card-header">
<h5 class="mb-0"> </h5>
</div>
<div class="card-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ route('add_article.newarticle') }}">
<div class="form-group">
<label for="title" style="margin-bottom:0px;">
Title:
</label>
<input class="form-control" type="text" name="title" placeholder="Please enter your title!" id="title">
#if ($errors->has('title'))
{{ $errors->first('title') }}
#endif
</div>
<div class="form-group">
<label for="content" style="margin-bottom:0px;">
Content:
</label>
<textarea class="form-control" rows="3" name="content" placeholder="Please enter your message!" id="content" style="resize:none;"></textarea>
#if ($errors->has('content'))
{{ $errors->first('content') }}
#endif
</div>
<div class="form-group text-right">
<button class="btn btn-primary" type="submit">
Create news
</button>
</div>
{{ csrf_field() }}
</form>
</div>
</div>
</div>
</div>
#endsection
I hope someone can help me to resolve this issue!
use App\Http\Requests;
Remove This from HomeController.php and try.
Your validation is passing but you are not doing anything after so it's not going to show anything unless you tell it to.
Also make sure you use $request->all() instead of $request in the validator as the first one will return the actual input values that were submitted.
use Validator;
public function post_article(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|max:64',
'content' => 'required|max:2048',
]);
if ($validator->fails()) {
return redirect('home')
->withErrors($validator)
->withInput();
}
// $newNews = new News;
// $newNews->title = $request->title;
// $newNews->content = $request->content;
// $newNews->save();
return redirect()->route('home')->with('message', 'Article created.');
}
}
Then in your view add the following at the top:
#if(Session::has('message'))
<div class="alert alert-success">
×
{{ Session::get('message') }}
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Based on those validation rules you will only see errors when the title is empty or longer than 64 characters, or the content is empty or longer than 2048 characters. Make sure the data you are testing with is long enough to trigger any errors.
For data that passes validation the code currently does not save (commented out), nor does it return a new location or view so it will show a blank page. You should probably save the data and redirect to the index or a show page with a success message.