I just wanted to ask how can we avoid this kind of output from arrayed input. Every time I update it, these symbols ["\"[ keeps on multiplying. I'll show you the problem and the code below.
Thank you your future answers.
Route::resource('setups','SetupController');
public function index()
{
$data = DB::table('setups')->first();
if (!empty($data)) {
$socials = explode(',',$data -> social);
}else{
$socials = [];
}
return view ('adminpanel.setup.index',['data' => $data,'socials' => $socials]);
}
index.blade.php
<form action="{{ route('setups.edit',$data->id) }}">
<div class="row">
<div class="col-md-12" id="socialGroup">
#foreach($socials as $social)
<div class="form-group socialField">
<label class="bmd-label-floating">Social Links</label>
<input type="text" name="social[]" value="{{$social}}" class="form-control" disabled>
<i class="fa fa-plus"></i>
</div>
#endforeach
<div class="alert alert-danger" id="socialError">
<p><strong>Sorry! </strong>You've reached the max number for social links form.</p>
</div>
</div>
</div>
<form>
.
public function edit($id)
{
$data = DB::table('setups')->first();
$setup = DB::table('setups')->where('id', $id)->first();
if (!empty($data)) {
$socials = explode(',',$data -> social);
}else{
$socials = [];
}
if($setup){
return view ('adminpanel.setup.edit',['data' => $data,'socials' => $socials]);
}else{
return redirect('setups');
}
}
.
edit.blade.php
<form method="POST" action="{{ route('setups.update', $data->id) }}">
<div class="row">
<div class="col-md-12" id="socialGroup">
#foreach($socials as $social)
<div class="form-group socialField">
<label class="bmd-label-floating">Social Links</label>
<input type="text" name="social[]" value="{{ $social }}" class="form-control">
<i class="fa fa-plus"></i>
</div>
#endforeach
<div class="alert alert-danger" id="socialError">
<p><strong>Sorry! </strong>You've reached the max number for social links form.</p>
</div>
</div>
</div>
<form>
.
public function update(Request $request, Setup $setup)
{
$data = Input::except('_token', 'submit', '_method');
$tbl = decrypt($data['tbl']);
unset ($data['tbl']);
$data['updated_at'] = date('Y-m-d H:i:s');
DB::table($tbl)->where(key($data), reset($data))->update($data);
session::flash('message','Setup updated successfully!!!');
return redirect()->route('setups.index');
}
Solved! I just added this code in my SetupController#update to illuminate those unwanted divider or separator(whatever) before
sending to database.
if (Input::has('social')) {
$data['social'] = implode(',',$data['social']);
}
laravel escaped data by default. It was not giving any error,whenever
you retrieve data from database to throw in your blade view.Database
data escaping is good practice.
As you showed your data,there is some unwanted data.Before you attempt to save your data,you may trim($yourString) to remove unwanted white-space from start & end of a string.
And You must not let blank or empty string to view in your blade. So, you might use blank($var) to check whether it is blank or not?
<form method="POST" action="{{ route('setups.update', $data->id) }}">
<div class="row">
<div class="col-md-12" id="socialGroup">
#foreach($socials as $social)
#if(!blank($social))
<div class="form-group socialField">
<label class="bmd-label-floating">Social Links</label>
<input type="text" name="social[]" value="{{ $social }}" class="form-control">
<i class="fa fa-plus"></i>
</div>
#endif
#endforeach
<div class="alert alert-danger" id="socialError">
<p><strong>Sorry! </strong>You've reached the max number for social links form.</p>
</div>
</div>
</div>
Solved! I just added this code in my SetupController#update
if (Input::has('social')) {
$data['social'] = implode(',',$data['social']);
}
Related
How to show an old value / query field from database in mysql, and edit value in Laravel. I'm using Laravel 9x and PHP 8x
Controller.php :
public function edit(Business $business)
{
return view('dashboard.bisnis.edit', [
'item' => $business
]);
}
public function update(Request $request, Business $business)
{
$rules = [
'deskripsi' => 'required|max:255',
'pemilik' => 'required|max:255'
];
$validateData = $request->validate($rules);
Business::where('id', $business->id)->update($validateData);
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
}
Blade.php:
#extends('dashboard.index')
#section('container')
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">Edit Data Bisnis</h1>
</div>
<div class="col-lg-8">
<form method="post" action="/dashboard/bisnis/{{ $item->id }}" class="mb-5" enctype="multipart/form-data">
#method('put')
#csrf
<div class="mb-3">
<label for="deskripsi" class="form-label">Deskripsi</label>
<input type="text" class="form-control #error('deskripsi') is-invalid #enderror" id="deskripsi" name="deskripsi" required autofocus
value="{{ old('deskripsi', $item->deskripsi) }}">
#error('deskripsi')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="mb-3">
<label for="pemilik" class="form-label">Pemilik</label>
<input type="text" class="form-control #error('pemilik') is-invalid #enderror" id="pemilik" name="pemilik" required autofocus
value="{{ old('pemilik', $item->pemilik) }}">
#error('pemilik')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<button type="submit" class="btn btn-primary">Simpan Perubahan</button>
</form>
</div>
<script>
const deskripsi = document.querySelector('#deskripsi');
const pemilik = document.querySelector('#pemilik');
</script>
#endsection
Also when navigating through my menu such as Business, the sidebar seems cant to be clicked, nor use. Thank you so much
Please try like this:
{{ old('deskripsi') ? old('deskripsi') :$item->deskripsi }}
Please replace this:
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
to
return redirect()->back()->with('success', 'Item has been updated !');
I assume you use Laravel 9
Referring to Repopulating Forms - Validation
Controller.php:
you should use
$deskripsi = $request->old('deskripsi');
$pemilik = $request->old('pemilik');
before
$validateData = $request->validate($rules);
Blade.php:
you should use this on input
value="{{ old('deskripsi') }}"
value="{{ old('pemilik') }}"
By default old will return null if no input exists so we don't need to use nullcheck like
{{old('deskripsi') ?? ''}}
To repopulate value using old() in Laravel you need to return a response withInput(). Not just response.
The return code should
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
change to this
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !')->withInput();
The solution is i forgot to pass my $id on my controller and route (web.php). Here's my route
Route::controller(GroupServiceController::class)->middleware('auth')->group(function () {
Route::get('/dashboard/gruplayanan', 'index');
Route::get('/dashboard/gruplayanan/create', 'create')->name('gruplayanan.create');
Route::post('/dashboard/gruplayanan', 'store')->name('gruplayanan.store');
Route::get('/dashboard/gruplayanan/edit/{id}', 'edit')->name('gruplayanan.edit');
Route::post('/dashboard/gruplayanan/update/{id}', 'update')->name('gruplayanan.update');
Route::post('/dashboard/gruplayanan/delete/{id}', 'destroy')->name('gruplayanan.delete');
});
and my controller :
public function edit(GroupService $groupService, $id)
{
$groupService = $groupService->findOrFail($id);
return view('dashboard.gruplayanan.edit', [
'item' => $groupService
]);
}
I want to upload more than one image at a time through an in Laravel 8 to my SQL database, and I am not able to do it. I have managed to upload only one, but when I try with more I get failure.
My Database
Imagenes
id
nombre
id_coche
01
name.jpg
0004
...
...
...
My Code
Blade with the Form
#foreach ($Vehiculo as $obj) /*this is to take the Car ID*/
<form method="POST" action="{{ route('añadirImagen')}}" enctype="multipart/form-data" >
#csrf
<div class="form-row">
<div class="form-group col-md-3">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">ID</span>
</div>
<input type="text" class="form-control" name="id_coche" value="{{$obj->id}}" style="background: white" required readonly>
</div>
</div>
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" required multiple/>
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-success">AÑADIR IMAGENES</button>
</div>
</div>
</form>
#endforeach
Controller
"To upload only one image"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'nombre.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->file("imagen")!=null){
$nombre = $request->file('imagen');
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
$Imagenes->save();
return redirect()->back()->with('error','Se han añadido las imagenes correctamente.');
}
}
"My attempt to upload more than one"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'imagen.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->hasfile("imagen")){
$nombre_img = $request->file('imagen');
foreach($nombre_img as $nombre) {
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
}
$Imagenes->save();
When doing this, it adds in the database a single row, with the correct id_coche, the Auto_Increment does well the ID, but the name remains NULL.
Thank You.
You currently have:
<input type="file" class="form-control" name="imagen" required multiple/>
and it needs to be:
<input type="file" class="form-control" name="imagen[]" required/>
multiple attribute is not required.
Then you can do in your controller:
if($request->hasfile('imagen')) {
foreach($request->file('imagen') as $file)
{
...
}
}
Good evening , for school i am trying to create a simple CRUD app, using laravel 6 and mongoDB.
I can get read, update and delete working but creat fails with The POST method is not supported for this route. Supported methods: GET, HEAD.. I have searched the answers here and other sites but im stuck for 2 days now (could be something very silly but im not seeing it)
my routes are:
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/post/{_id?}', 'PostController#form')->name('post.form');
Route::post('/post/save/', 'PostController#save')->name('post.save');
Route::put('/post/update/{_id}', 'PostController#update')->name('post.update');
Route::get('/post/delete/{_id}', 'PostController#delete')->name('post.delete');
form.blade is:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Post Form</div>
<div class="card-body">
#if($data)
<form action = "{{Route ('post.update', $data->_id)}}" method="post">
#csrf
#method('PUT')
<div class="form-group">
<label for="usr">Title:</label>
<input type="text" class="form-control" name="title" value = "{{$data->title}}" >
</div>
<div class="form-group">
<label for="comment">Content:</label>
<textarea class="form-control" rows="5" name="content">{{$data->content}}</textarea>
</div>
<p align="center"> <button class="btn btn-primary">save</button></p>
</form>
#else
<form action = "{{Route ('post.form')}}" method="post">
#csrf
<div class="form-group">
<label for="usr">Title:</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="comment">Content:</label>
<textarea class="form-control" rows="5" name="content"></textarea>
</div>
<p align="center"> <button class="btn btn-primary">save</button></p>
</form>
#endif
</div>
</div>
</div>
</div>
#endsection
and my PostController is:
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
//
public function form($_id = false){
if($_id){
$data = Post::findOrFail($_id);
}
$data = false;
return view ('post.form', compact('data'));
}
public function save (Request $request){
$data = new Post($request->all());
$data->save();
if($data){
return redirect()->route('home');
}else{
return back();
}
}
public function update (Request $request, $_id){
$data = post::findOrFail($_id);
$data->title = $request->title;
$data->content = $request->content;
$data->save();
/* return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]); */
if($data){
return redirect()->route('home');
}else{
return back();
}
}
public function delete($_id){
$data = post::destroy($_id);
if($data) {
return redirect()->route('home');
}
else {
dd('error cannot delete this post');
}
}
}
Anybody any idea what i am missing?
Thanks in advance
You have to replace this line <form action = "{{Route ('post.form')}}" method="post"> with <form action = "{{Route ('post.save')}}" method="post">
You are using wrong route. Please change to Route ('post.save')
EDIT: I found that one myself, the PostControler didnt return a view if there was an $_id
Thanks for the help everyone!
Thanks for pointing that out, it did bring my from back to life :) However it breaks the update function :S.
When i now click on the edit button, the form does no longer get filled with the data for the post, and "save" creates a new post in stead of updating it.
good day,
I new in laravel Framework and I face this two problems : -
first one
I want to redirect to my page after 2 seconds automatically.
the second one
I make custom function call (is exist )
if this function returns true data I want to print "name exist before " but the problem here is form was rested when this function returns true and print message.
how to prevent form resetting from inputs value?
here is my code
controller code
enter code here
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name'])))
{
$product=new productModel();
// start add
$product->name=$request->input('name');
$product->save();
$add=$product->id;
$poducten=new productEnModel();
$poducten->id_product=$add;
$poducten->name=$request->input('name');
$poducten->price=$request->input('price');
$poducten->save();
$dataview['message']='data addes';
}else{
$dataview['message']='name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my routes
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
I hope that I understood your question.
Instead of using {{ Request::old('price') }} use {{ old('price') }}
This should retrieve the form data after page was reloaded.
Try the below the code for error display in view page
$validator = Validator::make($params, $req_params);
if ($validator->fails()) {
$errors = $validator->errors()->toArray();
return Redirect::to($web_view_path)->with('errors', $errors);
}
You want to automatically redirect to another page submit the form using ajax and use below the settimeout menthod.
setTimeout(function(){ // Here mentioned the redirect query }, 3000);
//use $request instead of $_POST
if($request->isMethod('post'))
{
if(isset($request['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
Whenever I try to access /skills/add through an anchor in another page I get this error
The anchor that redirects to this page(with GET method) is:
<a class="btn icon-btn btn-success" href="/skills/add">
<span class="glyphicon btn-glyphicon glyphicon-plus img-circle text-success"></span>
Add
</a>
Tried using dd("test") to test it out but won't even work.
This are my routes for skills/add this:
Route::put('/skills/add', 'SkillsController#add');
Route::get('/skills/add', 'SkillsController#addIndex');
Here are my functions in SkillsController
public function addIndex() {
if (Auth::check()) {
return view('skills.add');
} else {
return redirect('/home');
}
}
public function add(Request $request) {
/*Sets validation rules for Skill object*/
$skillRules = [
'name' => 'required|max:25|regex:/[1-9a-zA-Z ]\w*/',
];
if (Skills::where('name', '=', $request->name)->count() > 0) {
return redirect('/skills')->with('message', "EXISTS");
}
$validator = Validator::validate($request->all(), $skillRules);
if ($validator == null) {
$newSkill = new Skills;
$newSkill->name = strtolower($request->name);
$newSkill->save();
return redirect('/skills')->with('message', "CREATED");
}
}
the skills.add view is this
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Edit Skill</h1>
<form method="POST" action="/skills/add">
{{method_field('PUT')}}
{{csrf_field()}}
<div class="row">
<div class="col-lg-5">
<div class="form-group">
Name:
<input name="name" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Skill</button>
<button type="button" class="btn btn-danger">Cancel</button>
</div>
</div>
</div>
</form>
</div>
#endsection
Not sure what happened, if someone in the future has this same problem, I literally just deleted and made manually thee controller, model and blade and it started to work. Not a lot of science or explain, sorry for that.
Change your route to named ones
Route::GET('/skills/add', 'SkillsController#addIndex')->name('addSkills');
Route::POST('/skills/add', 'SkillsController#add')->name('saveSkills');
and your blade to
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Edit Skill</h1>
<form method="POST" action="{{route('saveSkills')"> //** Change this
{{csrf_field()}}
<div class="row">
<div class="col-lg-5">
<div class="form-group">
Name:
<input type="text" name="name" class="form-control"> //** Change this
</div>
</div>
//Remaining form groups
</div>
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Skill</button>
<button type="button" class="btn btn-danger">Cancel</button>
</div>
</div>
</div>
</form>
</div>
#endsection
Change your anchor tag's href value to named route like
<a class="btn icon-btn btn-success" href="{{route('addSkills')}}">
<span class="glyphicon btn-glyphicon glyphicon-plus img-circle text-success"></span>
Add
</a>
and your controller
// SHOW ADD NEW SKILL FORM
public function addIndex() {
if (Auth::check()) {
return view('skills.add'); //view path is skills->add.blade.php
} else {
return redirect('/home');
}
}
//SAVE ADD NEW SKILL FORM DATA
public function add(Request $request) {
dd($request->name); //Check if value is getting
/*Sets validation rules for Skill object*/
$skillRules = [
'name' => 'required|max:25|regex:/[1-9a-zA-Z ]\w*/',
];
$validator = Validator::validate($request->all(), $skillRules);
if (Skills::where('name', '=', $request->name)->count() > 0) {
return redirect('/skills')->with('message', "EXISTS");
}
if ($validator == null) {
$newSkill = new Skills;
$newSkill->name = strtolower($request->name);
$newSkill->save();
return redirect('/skills')->with('message', "CREATED");
}
}
also add use App\RampUp\Skills; on top of controller
Sorry but there is no POST-route for <form method="POST" action="/skills/add">
maybe the POST is still executed.
On the other hand most Route errors could be resolved by clearing the cache (if present), rearranging the routes or put a group in between like
Route::group(['prefix' => 'skills'], function() {
Route::put('/add', 'SkillsController#add');
Route::get('/add', 'SkillsController#addIndex');
}