I'm new on Laravel framework. I'm trying to save from forms to database.
Example:
Input STEAM_ID:
Input Access:
Controller:
public function admins_add()
{
$serveradmins = DB::table('server_admins')->first();
$this->title('Add admins');
$this->pageView('servers::admins_add', ['serveradmins' => $serveradmins]);
DB::table('server_admins')->insert(
array(
$serveradmins->auth = Input::get('steam-id'),
$serveradmins->access = Input::get('access'),
$serveradmins->password = 'nopass',
$serveradmins->flags = 'ce',
$serveradmins->added_by = Input::get('added_by')
)
);
$serveradmins->save();
return Redirect::back();
}
Views:
<div class="page page-servers page-servers-admin-form">
<form method="POST" action="/admin/servers/admins/create" accept-charset="UTF-8" class="form-horizontal">
<div class="form-group ">
<label for="title" class="col-sm-3 control-label">STEAM ID</label>
<div class="col-sm-9">
<input name="steam-id" type="text" id="steam-id">
</div>
</div>
<div class="form-group ">
<label for="access" class="col-sm-3 control-label">Teisės</label>
<div class="col-sm-9">
<input name="access" type="hidden" value="" id="access">
<select id="access" name="access"><option value="" selected="selected">-</option>
<option value="abcdefghijklmnopqrstuv">Owner</option>
<option value="bcdfijmnopqruv">Admin</option>
<option value="3" disabled>PREMIUM</option>
</select>
</div>
</div>
<div class="form-actions">
<button type="submit" name="_form_submit" class="btn btn-default" value="1">
<i class="fas fa-save "></i>
SAVE!
</button>
<button type="button" onclick="document.location.href='/admin/servers/admins'" class="btn btn-default">
<i class="fas fa-times "></i> Cancel
</button>
</div>
</form>
</div>
</section>
And my routes:
ModuleRoute::get('admin/servers/admins/create', 'AdminServersController#admins_add');
ModuleRoute::post('admin/servers/admins/create', 'AdminServersController#admins_add');
Dont be mad on my if my code is terrible, i'm new on laravel and really like it! Thanks guys for helping :)
First: Why do you want to execute admins_add() in your get route? Create a function called index() for easier understanding and tell that function to return the view like
public function index() {
$serveradmins = DB::table('server_admins')->first();
return view('viewname')->with('serveradmins', $serveradmins);
}
Then your admins_add()should look like this:
public function admins_add(Request $request)
{
ServerAdmin::create([
'auth' => $request->steam-id,
'access' => $request->access,
'password' => 'nopass',
'flags' => 'ce',
'added_by' => $request->added_by
]);
return Redirect::back();
}
And before executing generate the ServerAdmin Model via CLI ( php artisan make:model ServerAdmin) and inside this model you change the fillables to
protected $fillable = [
'auth',
'access',
'password',
'flags',
'added_by'
];
and set
protected $table = 'server_admins';
Edit: As N Mahurin mentioned in the comments - take this solution for practicing with Laravel. Mass Assignments have a heavy security risk. Read here about it:
https://laravel.com/docs/5.6/eloquent#mass-assignment
Your insert is off. It should be key => value pairs (where the key is the column name in the DB). Try
DB::table('server_admins')->insert([
'auth' => Input::get('steam-id'),
'access' => Input::get('access'),
'password' => 'nopass',
'flags' => 'ce',
'added_by' => Input::get('added_by')
]);
See https://laravel.com/docs/5.6/queries#inserts for more info. You can also go the eloquent route and do:
$serverAdmin = new ServerAdmin();
$serverAdmin->auth = Input::get('steam-id'),
$serverAdmin->access = Input::get('access'),
$serverAdmin->password = 'nopass',
$serverAdmin->flags = 'ce',
$serverAdmin->added_by = Input::get('added_by')
$serverAdmin->save();
Related
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)
{
...
}
}
I have multiple data base connection when I validate name of product I send message product name is exist before to view and here problem is appeared.
Message appeared in view but all form inputs is cleared.
How I recover this problem taking in consideration if product name not exist. validation executing correctly and if found error in validation it appeared normally and form input not cleared.
this my controller code.
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
$query = dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name']));
if(!$query) {
$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 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
this is my route
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
You can create your own custom validate function like below. I guess this should help you.
Found it from https://laravel.com/docs/5.8/validation#custom-validation-rules -> Using Closures
$validationarray = $this->validate($request,
[
'name' => [
'required',
'alpha',
function ($attribute, $value, $fail) {
//$attribute->input name, $value for that value.
//or your own way to collect data. then check.
//make your own condition.
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$value))) {
$fail($attribute.' is failed custom rule. There have these named product.');
}
},
],
'price' => [
'required',
'numeric',
]
]);
First way you can throw validation exception manually. Here you can find out how can you figure out.
Second way (I recommend this one) you can generate a custom validation rule. By the way your controller method will be cleaner.
Basically i have this form on userblog/create.blade.php
<form action="{{route('userblog.store')}}" method="POST">
{{csrf_field()}}
<div class="form-group">
<div class="row">
<div class="col-md-12">
<label style="font-family: SansBold">تیتر وبلاگ:</label>
<input type="text" name="blog_title"
class="form-control">
</div>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn btn-primary">
Save
<i class="icon-arrow-left13 position-right"></i></button>
</div>
<br/>
</form>
with this route on web.php
Route::group(['middleware' => ['auth:web'], 'prefix' => 'page'], function () {
$this->resource('userBlog', 'UserBlogController');
});
now I'm trying to check posted form on Controller with this code and store them on database:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'blog_title' => 'required|min:10',
'blog_content' => 'required|min:10',
]);
if ($validator->failed()) {
return back();
} else {
dd('store on database');
}
}
in this my code i get
Route [userblog.store] not defined
error and when i change form action to /page/userBlog i get [] on $validator
The routes name should be like resource name. Replace your resource name or Route name like:
$this->resource('userblog', 'UserBlogController');
or
.. action="{{route('userBlog.store')}}"
BTW, It's not a validation error. Just fix your route.
I have login form with two text fields email, password.when I tried to login with credentails it's working fine but when clear cache and then tried to login it gives the 'MethodNotAllowedHttp' exception.I am not getting the issue why it's showing this error. My code is as follows:
Route::post('users/login/5', 'administrator\usersController#login')->name('sl');
usersController.php
namespace App\Http\Controllers\administrator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Validator;
use Session;
class FreeusersController extends Controller {
function login(Request $request) {
$type = $request->segment(3);
//print_r($request);
echo "type=".$type;
echo $request->input('email');
echo $request->input('password');
die("sss");
if ($request->isMethod('post') && !empty($type)) {
$this->validate($request, [
'email' => 'required|min:5,max:50',
'password' => 'required|min:5,max:50'
]);
switch ($type) {
case 5:
$condArr = ['email' => $request->input('email'), 'password' => $request->input('password'), 'type' => '5', 'role' => 'father'];
break;
case 4:
$condArr = ['email' => $request->input('email'), 'password' => $request->input('password'), 'type' => '4', 'status' => true];
break;
}
if (Auth::attempt($condArr)) {
return redirect('administrator/dashboard');
} else {
return redirect(url()->previous())->withErrors(['password' => 'Invalid credentials'])->withInput();
}
} else {
return redirect("/");
}
}
}
<form action="/users/login/5" id="login-form" method="post" class="smart-form client-form">
{{ csrf_field() }}
<fieldset>
<section>
<label class="label">Email</label>
<label class="input"> <i class="icon-append fa fa-user"></i>
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}">
</section>
<section>
<label class="label">Password</label>
<label class="input"> <i class="icon-append fa fa-lock"></i>
<input id="password" type="password" class="form-control" name="password">
</section>
</fieldset>
<footer>
<button type="submit" class="btn btn-primary">
LogIn
</button>
</footer>
</form>
You have to clear routes:
php artisan route:cache
Then it will remember that login action is post.
I think you are getting this error because you when you are calling this url there is another url with something like users/{id} which means anything after users/. May be you are using resource route. So, when you call url users/login/5 its taking login/5 as $id of that users/{id} url.
But that url is for GET method. You are calling this with post method, as a result you are getting this error.
Solution
You can try calling your url using route method like:
action="{{route('sl', ['id'=>5])}}"
If it doesn't work then you can change your route to something else. For example:
Route::post('user/login/5', 'administrator\usersController#login')->name('sl');
Here you can use user instead of users because you already have a url with a users. Don't forget to change your action too.
First look at your routes with php artisan route:list.
Then are you sure of your request verb ? Look in your navigator console to look at your requests.
I am getting the check box values(multiple values) from view where user select the topics they are interested and store multiple values in a column in my database. So used serialize() to store them in my database. When i try to do that. It throws me the above mentioned error. I went through previous questions in Stackoverflow and did few changes like
$data = array(
'topics' => $post['topics'] ,);
to
$data = [
'topics' => $post['topics'] ,];
Again it shows the same error , Here is my View
<div class="panel-body">
<center><h2> Select the topic you are interested in</h2></center><br>
<form enctype="multipart/formdata"class="form-horizontal" role="form" method="POST" action="{{ url('/topicStore') }}">
{{ csrf_field() }}
<center>
<input type="checkbox" name="topics[]" value="sports"> Sports</input>
<input type="checkbox" name="topics[]" value="education"> Education</input>
<input type="checkbox" name="topics[]" value="family"> Family</input>
<input type="checkbox" name="topics[]" value="friends"> Friends</input></center><br>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-user"></i>Add topics
</button>
</div>
</div>
</div>
Here is my controller.
public function storeSelection(Request $request)
{
$post = $request->all();
$val=\Validator::make($request->all(),
[
'topics' => 'required',
]);
if ($val ->fails())
{
return redirect()->back()->withErrors($val->errors());
}
else
{
$data = array(
'topics' => $post['topics'] ,
);
$topics = serialize($data);
$updatedata = DB::table('users')->where('name',\Auth::user()->name)
->update($data);
if ($updatedata>0) {
return redirect('home');
}
}
}
I want to save the array of data which i get from the view to a column in database. I have used serialize(). Are there any other better ways to do this ?