I have a small project with laravel and I stuck on my create method inputs. So this is happening:
When I click on my input to type something it is showing my old values. How can I get rid of that?
Here is my Controller#store function:
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if(Auth::user()->name == 'Optika Podgorica/Delta'){
$this->validate($request, [
'br_kesice' => 'required',
'klijent' => 'required',
'datum_preuz' => 'required',
//'datum_izdav' => 'required',
]);
$storeone = new Storeone;
$storeone->br_kesice = $request->input('br_kesice');
$storeone->klijent = $request->input('klijent');
$storeone->br_telefona = $request->input('br_telefona');
$storeone->posao = $request->input('posao');
$storeone->cijena = $request->input('cijena');
$storeone->placanje = $request->input('placanje');
$storeone->popust = $request->input('popust');
$storeone->datum_preuz = $request->input('datum_preuz');
$storeone->datum_izdav = $request->input('datum_izdav');
$storeone->smjena = $request->input('smjena');
$storeone->radnik = $request->input('radnik');
$storeone->status = $request->input('status');
$storeone->user_id = auth()->user()->id;
$storeone->save();
return redirect('/storeones');
}else{
return redirect()->back();
}
}
And I use Laravel Collective forms. Can anybody help me?
I think it's coming form browser auto fill. Add autocomplete="false" to your input it will not show previous entry.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 months ago.
Improve this question
I am submitting a form thorugh ajax, form values are saving in the database and errors are showing without page reload, which is a good thing. As I am a beginner so i cannot make sense of this error. This error is not disturbing or impacting the flow of the application in any way. Thanks.
**Here's the error's image: **
**Here's the code of the controller: **
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Products;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Validator;
class ProductController extends Controller
{
//Search Products
public function search(Request $request)
{
$products = Products::where('name','like', '%'.$request->search.'%')
->orWhere('id','like', '%'.$request->search.'%')->get();
$output = "";
foreach($products as $products)
{
$output.=
'<tr class="border-bottom border-dark p-3">
<td>'.$products->name.'</td>
<td>'.$products->s_description.'</td>
<td>'.$products->l_description.'</td>
<td class="align-center p-5"><img class="img-fluid" src='.asset('images')."/".$products->image_src.'></td>
<td>'.$products->category.'</td>
<td>'.$products->quantity.'</td>
<td>'.$products->price.'</td>
<td>'.'
<form action='.route('delete_product', $products->id).' method="POST" id="deleteBtn">
z
<input type="hidden" name="_method" value="delete">
<button class="btn btn-danger" type="submit">'.'Delete</button>
</form>
'.'
</td>
</tr>
';
}
return response($output);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function viewProducts()
{
$p_details = Products::all();
return view('admin.products.view_products', compact('p_details'));
}
public function productVerify(Request $request)
{
$val = $request->validate
(
[
'name' => 'required',
's_description' => 'required',
'l_description' => 'required',
'image_src' => 'required|mimes:jpg,png,jpeg',
'category' => 'required',
'quantity' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',
'price' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',
],
[
'required' => 'The :attribute field is required',
'mimes' => 'Image should be a JPG, JPEG, or PNG',
'integer' => 'The :attribute field should be an integer.',
]
);
if ($val)
{
return response()->json(['errors'=>($val)->errors()->all()]);
}
else
{
// return redirect()->to('view_products')->with('success','Product added successfully');
return response()->json(['errors'=>'Product added successfully, head to view products to inspect it. Thanks!']);
}
}
//Uploading Images
public function validImg(Request $request)
{
if ($request->hasFile('image_src'))
{
$filename = $request->file('image_src');
$filename->getClientOriginalName();
$filename = time().$filename->getClientOriginalName();
$destinationPath = base_path("/public/images");
$request->file('image_src')->move($destinationPath, $filename);
$data['image_src'] = $filename;
}
return $data['image_src'];
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.products.add_products');
}
//Creating and Adding Products
public function createProduct(Request $request)
{
//Product Validation
$validation = $this->productVerify($request);
$data = $request->all();
$image_src = $this->validImg($request);
Products::create
([
'name' => $data['name'],
's_description' => $data['s_description'],
'l_description' => $data['l_description'],
'category' => $data['category'],
'quantity' => $data['quantity'],
'price' => $data['price'],
'image_src' => $image_src
]);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$product_edit = Products::findOrFail($id);
return view('admin.products.edit_products', compact('product_edit'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//Product Validation
$validatedData = $this->productValidation($request);
$this->validImg($request);
Products::whereId($id)->update($validatedData);
return redirect('view_products')->with('success', 'Product details successfully updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$products = Products::findOrFail($id);
$destinationPath = base_path("/public/images").'/'.$products->image_src;
if(File::exists($destinationPath))
{
File::delete($destinationPath); //for deleting only file try this
$products->delete(); //for deleting record and file try both
}
// $products->delete();
return redirect('view_products')->with('error', 'Product successfully deleted');
}
}
The validate() method on the $request object returns an array (see API docs) containing the data that passed validation. If validation fails, a JSON response (which includes validation errors) is generated and returned to the client that made the request.
The code statement you're highlighting in your question is informing you that the variable $val is an array, however, you're attempting to access some data within $val using the object operator (->) as though it were an object.
If that code statement were to actually be executed, you'd see an exception message because of this (there is no errors() method on the $val array).
I've used the #method('PUT') in my blade, but it still says the PUT Method is not supported, does someone know what's wrong?
My routes are:
routes
This is my workshops controller edit parameter and storage.
public function edit(Workshops $workshops)
{
$result = compact('workshops');
Json::dump($result);
return view('admin.workshops.edit', $result);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Workshops $workshops
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Workshops $workshops)
{
$this->validate($request,[
'name' => 'required|unique:workshops' . $workshops->id,
'datum' => 'required'. $workshops->id,
'plaatsen' => 'required' . $workshops->id,
'price' => 'required'
]);
$workshops->name = $request->name;
$workshops->datum = $request->datum;
$workshops->plaatsen = $request->plaatsen;
$workshops->price = $request->price;
$workshops->save();
session()->flash('success', 'The workshop has been updated');
return redirect('admin/workshops');
}
Look in your routes file, you need Route::put() for the route you are trying to use. https://laravel.com/docs/7.x/routing#basic-routing
You need to define your route with PUT as shown below
Route::put('/admin/workshops/{id}', 'ControllerName#methodName');
Official Laravel Documentation
W3Schools
You have to use like this
Route::post('/admin/workshops/{id}', 'ControllerNameController#methodName');
I want to pass $params['user_id'] to $fieldValidations and check if the hour is unique for specific user_id not for all hours hour in the database table
I created a model post
class Post extends Model
{
protected $fillable = ['user_id', 'hour'];
public static $fieldValidations = [
'user_id' => 'required',
'hour' => 'required|date_format:Y-m-d H:i:s|unique:post,hour,NULL,user_id,'
];
}
and a controller post
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$params = $request->all();
$params['user_id'] = 12;
$validator = Validator::make($params, Post::$fieldValidations);
if ($validator->fails()) {
return Response::json($validator->errors()->all(), 422);
}
}
}
I don't think you can do this using the unique validation rule. From Laravel 5.7 documentation:
The field under validation must be unique in a given database table.
Note it says table and not column.
You may have to just query the database and return a JSON response error if it fails. Also, in your current code inside the validation rules, you are specifying that user_id is the primary id key column in the post table. I think that is likely an error and should be removed, even though it's irrelevant given that you can't accomplish what you want using the unique rule. Also, you ended the rule with a comma.
if (Post::where(['user_id' => $params['user_id'], 'hour' => $params['hour']])->exists()) {
return response()->json(['status' => 'error', 'msg' => 'Error', 'errors' => ['hour_error' => ['That hour already exists on the user!']]], 422);
}
Lastly, instead of using $params = $request->all(), I prefer to use the request() helper function and just inline it into the rest of the code. But, that's up to you.
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request) {
$rules = [
'translations' => 'required|array',
'translations.*.language_code' => 'required|exists:app_languages,code',
'translations.*.name' => 'required'
];
$this->validate($request, $rules);
dd("OK");
}
I am using PostMan to test it. Everything is ok for array's second parameter. But it does not accept name 0 index or array.
When i didn't send first index :
UPDATE
It is Postman's bug. I added same parameter then replace it, it works.
It is Postman's bug. I added same parameter then replace it, it works.
I do not know, why it didn't accept and now it accept lol.
I think this helps you .
$rules = [];
if($request->has('translations'))
{
$translations = $request->input('translations');
foreach($translations as $key => $value)
{
$rules["translations.$key.$value"] = 'required';
}
}
I am trying to populate two columns with random strings whenever a new user is created in laravel
maybe something like this in User model
public function putStringInDatabase () {
$this->public_key = str_random(40);
}
and whenever a new row is added in users table public_key and private_key columns get updated automatically by that random string
Take a look at Model Events. Specifically creating.
For example:
User::creating(function($user) {
$this->public_key = str_random(40);
$this->private_key = str_random(40);
});
http://php.net/manual/en/function.uniqid.php
Try making the string unique!
You could do it in the controller when you are creating the record
/**
* Create a new Object instance.
*
* #param array $data
*
* #return Object
*/
protected function create(array $data)
{
$object = new Object([
'fields' => $data['values']
'email' => $data['email'],
]);
$object->public_key = str_random(40);
$object->save();
return $object;
}
This will let you add a public_key outside of the mass assignment.