Data is again added to the database after reloading the page - php

Whenever I am directed to ad page and then reload same data is again entered in the database. Is there any other of redirecting of page while keeping those compact variables???
Controller.php
public function StorePost(Request $request)
{
$formInput = $request->except('image');
$this->validate($request, [
'title' => 'required',
'name' => 'required',
'email' => 'required|email',
'contact' => 'required',
'model' => 'required',
'city' => 'required',
'description' => 'required',
'image'=>'image|mimes:png,jpg,jpeg|max:10000'
]);
$image = $request->image;
if($image){
$imageName = $image->getClientOriginalName();
$image->move('images',$imageName);
$formInput['image'] = $imageName;
}
Post::create($formInput);
$posts = Post::all();
return view('ad.ad',compact('name','posts'));
}}

You may want to simply redirect (redirect('/ad_url')) to the 'ad' route/page. Lets say maybe 'ControllerForAddPage' is the one that displays your 'ad' view, simply instead fetch all the posts in that controller and not in the controller that handles saving your data.

I think it's better to use different route between store and show. you just need to redirect to index route after store success. ex:
...
Post::create($formInput);
return redirect()->route('ad.index');

You should redirect to different location to avoid this. If data is successfully store then redirect it to posts list url otherwise to the same location again with error message.
Example code is follows:
public function StorePost(Request $request) {
$formInput = $request->except('image');
$this->validate($request, [
'title' => 'required',
'name' => 'required',
'email' => 'required|email',
'contact' => 'required',
'model' => 'required',
'city' => 'required',
'description' => 'required',
'image' => 'image|mimes:png,jpg,jpeg|max:10000'
]);
$image = $request->image;
if ($image) {
$imageName = $image->getClientOriginalName();
$image->move('images', $imageName);
$formInput['image'] = $imageName;
}
$store = Post::create($formInput);
if($store){
//return to posts list view
return redirect('posts')->with('success', 'Post successfully stored.');
}
//redirect to the form to create post
return redirect()->back()->with('failed', 'Failed to store the post!');
}

Related

How can i upload a picture in laravel?

i'm trying to insert a product with a picture into my database , but when i submit nothing get inserted .
i tried to add 'Image1' => 'required|Image' but i get Unable to guess the MIME error
This is the Store method
public function store(Request $request)
{
$data = request()->validate([
'Name' => 'required',
'Title' => 'required',
'category' => 'required',
'MainPrice' => 'required',
'MainPrice' => 'required',
'StockQuantity' => 'required',
'Discription' => 'required',
'Features' => 'required',
'Image1' => 'required'
]);
$imagePath =request('Image1')->store('uploads', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1200, 1200);
$image ->save();
$query = DB::table('products')->insert([
'Name' => $request->input('Name'),
'Title' => $request->input('Title'),
'category' => $request->input('category'),
'MainPrice' => $request->input('MainPrice'),
'DiscountPrice' => $request->input('DiscountPrice'),
'StockQuantity' => $request->input('StockQuantity'),
'Discription'=> $request->input('Discription'),
'Features'=> $request->input('Features'),
'Image1'=> $imagePath
]) ;
if($query){
return back()->with('success', 'Data have been successfuly inserted');
}
else{
return back()->with('fail', 'Somethimg went wrong');
}
}
and this is the Route
Route::post('Product', [ProductsController::class, 'store']);
Any one faced the same problem ?
Your picture is probably in the wrong format. RTF is the most commonly used format, but it's not compatible with MySQL. You need an image format that supports transparency, such as GIF, JPG, or PNG.

How to fetch and store data from other table to user table. Laravel 8

Form
{!! Form::select('grade_level[]', $grade_level,[], array('class' => 'form-control','multiple')) !!}
Controller
Here is my create function that will return the a view and the list of roles and grade level for users
public function create()
{
$grade_level = GradeLevel::pluck('grade_level','id')->all();
$roles = Role::pluck('name','name')->all();
return view('users.create',compact('roles','grade_level'));
}
Here is the store function. and I have encounter a problem MySql Error: 1364 Field 'grade_level_id' doesn't have default value
public function store(Request $request)
{
$this->validate($request, [
'f_name' => 'required',
'm_name' => 'required',
'l_name' => 'required',
'sex' => 'required',
'id_number' => 'required',
'address' => 'required',
// 'email' => 'required|email|unique:users,email',
'username' => 'required|unique:users',
'password' => 'required|same:confirm-password',
'grade_level_id' => 'required',
'roles' => 'required'
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$user->grade_level_id = $request->grade_level;
$user->assignRole($request->input('roles'));
return redirect()->route('users.index')
->with('success','User created successfully');
}
I see you're using User::create() method to add new user, you'd need to add grade_level_id to the fillable property or your User model.
protected $fillable = [
'grade_level_id'
];
Find More about it here : https://laravel.com/docs/8.x/eloquent#mass-assignment
Either add 'grade_level_id' to the $fillable of your user model,
or
inside your migration, you can add the ->nullable(); extension to the grade_level_id field declaration

How can I save two models at the same time in Laravel?

I want to know how can I save two models which has one relationship in my models. I don't know how to save it but I need the ID for my patient model to assign to my scale model.
Here is my PatientController.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$scales = new Scale;
$patient->name = $request->input('name');
$scales->sd_abc_1_old = $request->input('sd_abc_1_old');
$patient->save();
return redirect('/patients')->with('success', 'Paciente creado.');
}
I try this code but get error.
DB::transaction(function() use ($patient, $scales) {
$patient = $patient->save(); //Patient Exists First
Patient::find($patient->id)->scales()->save($scales)
});
You could try something like this:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$patient->name = $request->name;
$patient->save();
$patient->scale()->create(['patient_id' => $patient->id, 'sd_abc_1_old' => $request->sd_abc_1_old]);
);
return redirect('/patients')->with('success', 'Paciente creado.');
}
If the model uses a hasOne() relation like you said then the code show work, with a bit of modification of course.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = Patient::create([
'name' => $request->input('name'),
]);
$scale = Scale::create([
'patient_id' => $patient->id,
'sd_abc_1_old' => $request->sd_abc_1_old,
]);
return redirect('/patients')->with('success', 'Paciente creado.');
}
First create and store base model and referencing it save related model
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$patient->name = $request->input('name');
$patient->save();
$scales = new Scale;
$scales->sd_abc_1_old = $request->input('sd_abc_1_old');
$patient->scales()->save($scales);
return redirect('/patients')->with('success', 'Paciente creado.');
}

Query String validation Laravel

I don't know how to get the query string array to validate in Laravel Validation.
here is my code
public function addUserByAdmin(Request $request){
$this->validate($request,[
'name' => 'required',
'fullname' => 'required',
'password' => 'required',
'position' => 'required',
'phone' => 'required'
]);
$uesrAction = new UserAction($this->repository);
$user = $uesrAction->addUser($request->input('phone'),$request->input('password'),$request->input('name'),$request->input('fullname'),$request->input('position'));
if($user){
return response()->json(['success' => 'success','user'=>$user]);
}
return response()->json(['success' => 'fail']);
}
but validation doesn't work.Then I tried Validation::make() method and also didn't work.
My URL be like
http://localhost:8000/admin/users/add-user?phone=abcdefg&password=erer&name=ere&fullname=rere&position=343
If you are using laravel 5.5, change your code as follows:
public function addUserByAdmin(Request $request){
$validatedData = $request->validate([
'name' => 'required',
'fullname' => 'required',
'password' => 'required',
'position' => 'required',
'phone' => 'required'
]);
// ...
}
One of the features that was added in this update is that other way to use the validate() method:
More info:
https://laravel.com/docs/5.5/validation#quick-writing-the-validation-logic
https://laravel.com/docs/5.5/releases

Validating image and storing image in specific folder

I am validating and storing image using my Controller.
When I validate image form is not stored in database but when I comment validation it stores in database.
FrontController.php
public function StorePost(Request $request)
{
$formInput = $request->except('image');
$this->validate($request, [
'title' => 'required',
'name' => 'required',
'email' => 'required|email',
'contact' => 'required',
'model' => 'required',
'city' => 'required',
'description' => 'required',
'image' => 'image|mimes:png,jpg,jpeg|max:10000'
]);
//image upload
$image = $request->image;
if($image){
$imageName = $image->getClientOriginalName();
$image->move('images', $imageName);
$formInput['image'] = $imageName;
}
Post::create($formInput);
$posts = Post::all();
return view('ad.ad', compact('name', 'posts'));
}

Categories