Laravel multiple delete checkbox? - laravel

I want to delete only checked tasks. At the moment I have this:
<form method="POST" action="/destroy">
#foreach($tasks as $t)
<label>
<input type="checkbox" name="checked[]" value="$t->id">
</label>
#endforeach
<button type="submit">Submit!</button>
</form>
This is my Controller
public function destroy(Request $request)
{
$this->validate($request, [
'checked' => 'required',
]);
$checked = $request->input('checked');
Task::destroy($checked);
}
And this is my route
Route::post('/destroy', [
'uses' => 'Controller#destroy',
]);
I don't get no error but the system does not work

I fixed the problem! Thanks for your support!
The problem was that my id variable was a hash.

Related

Show checkbox checked from database

Hope you're all fine.
I have an article, and I want to be able to edit it. Inside the article, I have checkboxs, and what I want is to check the ones I've checked when I first create the article (Im using a pivot table).
I have this code for now.
public function createArticle(Request $request)
{
$data = $request->validate([
'titreArticle' => 'bail|required|between:5,40',
'typeArticle' => 'bail|required',
'themeCheckbox' => 'required',
'themeCheckbox.*' => 'required',
'contenuArticle' => 'bail|required',
]);
$type_articles = Type_article::findOrFail($data['typeArticle']);
$article = new Article();
$article->type_article()->associate($type_articles);
$themes = Theme::whereIn('theme_id', array_keys($data['themeCheckbox']))->get();
$article->titre = $data['titreArticle'];
$article->contenu = $data['contenuArticle'];
$article->save();
$article->theme()->attach( $themes);
return view('admin');
}
And inside my view :
#foreach ($themes as $theme)
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" name="themeCheckbox[{{$theme->theme_id}}]" value="1" >
<label class="form-check-label">{{ $theme->nom_theme }}</label>
</div>
#endforeach
I've seen I must use contains but don't really know how to use it...
Cordially

Laravel request validation on array

Lets say I submit this form:
<form>
<input type="text" name="emails[]">
<input type="text" name="emails[]">
<input type="text" name="emails[]">
<input type="text" name="emails[]">
<input type="text" name="emails[]">
</form>
How do I then validate that at least one (anyone) of the $request->emails[] is filled?
I have tried this - however it does not work:
$request->validate([
'emails' => 'array|min:1',
'emails.*' => 'nullable|email',
]);
Laravel 7
Try this
$request->validate([
'emails' => 'array|required',
'emails.*' => 'email',
]);
Cordially
To meet your requirement, you may need custom rule
First create a rule, php artisan make:rule YourRuleName
inside YourRuleName.php
public function passes($attribute, $value)
{
foreach(request()->{$attribute} as $email) {
// if not null, then just return true.
// its assume in arrays some item have values
if ($email) { // use your own LOGIC here
return true;
}
}
return false;
}
Then,
$request->validate([
'emails' => [new YourRuleName],
]);

Update data in laravel 6

I try to create crud in laravel 6. Create, Read and Delete process is running well. But when Update process, the data in table not change. Could anyone help me to find the problem ? The following my code.
Route
Route::get('/blog', 'BlogController#index');
Route::get('/blog/add','BlogController#add');
Route::post('/blog/store','BlogController#store');
Route::get('/blog/edit/{id}','BlogController#edit');
Route::post('/blog/update','BlogController#update');
Controller
public function index()
{
$blog = DB::table('blog')->get();
return view('blog',['blog' => $blog]);
}
public function edit($id)
{
$blog = DB::table('blog')->where('blog_id', $id)->get();
return view('edit', ['blog'=>$blog]);
}
public function update(Request $request)
{
DB::table('blog')->where('blog_id',$request->blog_id)->update([
'blog_title' => $request->title,
'author' => $request->author]);
return redirect('/blog');
}
View
#foreach ($blog as $n)
<form method="post" action="/blog/update" />
{{ csrf_field() }}
Title <input type="text" name="title" value="{{ $n->title}}">
Author<input type="text" name="author" value="{{ $n->author}}">
<button type="submit" class="btn btn-secondary">Update</button>
</form>
#endforeach
You must provide id in your route
Route::post('/blog/update/{id}','BlogController#update');
In update method add parameter id and then find product against id
public function update(Request $request, $id)
{
DB::table('blog')->where('blog_id',$id)->update([
'blog_title' => $request->title,
'author' => $request->author]);
return redirect('/blog');
}
#foreach ($blog as $n)
<form method="post" action="{{ route('your route name'), ['id' => $$n->id] }}" />
{{ csrf_field() }}
Title <input type="text" name="title" value="{{ $n->title}}">
Author<input type="text" name="author" value="{{ $n->author}}">
<button type="submit" class="btn btn-secondary">Update</button>
</form>
#endforeach
try separating the update into two statements like so
$blog = DB::table('blog')->where('blog_id',$id)->first();
$blog->update([
'blog_title' => $request->title,
'author' => $request->author]);
Also you might want to use models in the future so you can do it like
$blog = Blog::where('blog_id',$id)->first();
Doesn't really shorten your code but it improves the readibility.
Do your update like this:
public function update(Request $request)
{
$post = DB::table('blog')->where('blog_id',$request->blog_id)->first();
$post->blog_title = $request->title;
$post->author = $request->author;
$post->update();
return redirect('/blog');
}

Import Excel to Database in laravel?

I'm trying to Import an excel file and save the info into the database table. Right now I'm getting an error
The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE.
All the tutorials I saw didn't get this error and I'm doing it the same way, I don't know what the issue is. I'm using this package "maatwebsite/excel": "~2.1.3".
This is my vue
<el-form :action="'impteachers/import'" method="post" enctype="multipart/form-data">
<el-input type="file" name="file"/>
<el-input type="submit" value="upload"/>
</el-form>
This is the controller
public function import(Request $request)
{
$request->validate([
'file' => 'required|mimes:xls,xlsx'
]);
$path = $request->file('file')->getRealPath();
$data = Excel::load($path)->get();
if ($data->count()) {
foreach ($data as $key => $value){
$arr[] = [
'NOMBRE' => $value->name,
'CEDULA' => $value->card,
'CARNET' => $value->scard,
'TIPO-USUARIO' => $value->user_type_id,
'CORREO' => $value->email,
'PASSWORD' => $value->password,
];
}
if (!empty($arr)) {
User::insert($arr);
}
}
return redirect('/imports');
}
These are the routes in web.php
Route::resource('impteachers', 'ImportTeacherController');
Route::post('impteachers/import', 'ImportTeacherController#import');
What am I doing wrong?
Try submitting to '/impteachers' only like this
<el-form :action="'/impteachers'" method="post" enctype="multipart/form-data">
<el-input type="file" name="file"/>
<el-input type="submit" value="upload"/>
</el-form>
And set your route to this
Route::post('/impteachers', 'ImportTeacherController#import');

Call to a member function getClientOriginalName() on null when upload image use file system Laravel

I want to upload an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image.
Call to a member function getClientOriginalName() on null
Controller
public function store(Request $request)
{
$admin = $request->all();
$fileName = $request->file('foto')->getClientOriginalName();
$destinationPath = 'images/';
$proses = $request->file('foto')->move($destinationPath, $fileName);
if($request->hasFile('foto'))
{
$obj = array (
'foto' => $fileName,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
}
return redirect()->route('admin-index');
}
View
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
Error
You can check wheather you are getting file or not by var_dump($request->file('foto')->getClientOriginalName());
And make sure your form has enctype="multipart/form-data" set
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
Error because of client Side
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
you ned to add enctype="multipart/form-data" inside the form
If You are using the form builder version
{!! Form::open(['url' => ['store'],'autocomplete' => 'off','files' => 'true','enctype'=>'multipart/form-data' ]) !!}
{!! Form::close() !!}
Then In your Controller You can check if the request has the file
I have Created the simple handy function to upload the file
Open Your Controller And Paste the code below
private function uploadFile($fileName = '', $destinationPath = '')
{
$fileOriginalName = $fileName->getClientOriginalName();
$timeStringFile = md5(time() . mt_rand(1, 10)) . $fileOriginalName;
$fileName->move($destinationPath, $timeStringFile);
return $timeStringFile;
}
And the store method
Eloquent way
public function store(Request $request)
{
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile= $this->uploadFile($request->foto,$destinationPath );
}
Admin::create(array_merge($request->all() , ['foto' => $fotoFile]));
return redirect()->route('admin-index')->with('success','Admin Created Successfully');
}
DB Facade Version
if You are using DB use use Illuminate\Support\Facades\DB; in top of your Controller
public function store(Request $request)
{
$admin = $request->all();
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile = $this->uploadFile($request->foto,$destinationPath );
}
$obj = array (
'foto' => $fotoFile,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
return redirect()->route('admin-index');
}
Hope it is clear

Resources