How To Show User Inputs After Registration Is Completed In Laravel - php

I am creating a website. In this website, I have created a Form. In this form, users can type their details and submit. When someone clicks submit button all the data stores into the database. But, Now I want to show User Inputs after registration is completed. I mean, there is page A which users can input and when this user clicks submit button I want to redirect that user to page B and show him, his inputs. I have tried this way, and it gives me this error -
ErrorException (E_ERROR)
Undefined variable: date (View: D:\wamp64\www\FinalProject\resources\views\addmoney\paywithpaypal.blade.php)
How can I Fix this ??
Form View Page Book.blade.php
<form class="form-horizontal" id="form1" method="POST" action="{{ route('booktsinsert') }}"
enctype="multipart/form-data">
{{ csrf_field() }}
<h4><span id="success_message" class="text-success"></span></h4>
<br>
<h4 style="font-family: Times New Roman;font-size:200%;color:blue;"> Book {{ $bk->title }} Movie </h4> <br>
<input type="hidden" name="Movieid" value="{{ $bk->id }}">
<div class="form-group row">
<label for="example-date-input" class="col-2 col-form-label">Select Date :</label>
<div class="col-10">
<input class="form-control" type="date" name="date" placeholder="mm-dd-yyyy"
id="example-date-input">
</div>
</div>
</form>
Redirect View page. ( paywithpaypal.blade.php )
<h1> {{$date}} </h1>
Controller page. ( BookSeatController.php )
public function booktsinsert(Request $request)
{
$Mid = $request->input('Movieid');
$date = $request->input('date');
$st = $request->input('st');
$sendemail = $request->input('email');
$user = new BookSeat();
$user->Movie_id = $Mid;
$user->sdate = $date;
$user->stime = $st;
$user->email = $sendemail;
$user->save();
}
return redirect('paywithpaypal')->with("date", $date);
}
}
Routes.
Route::post('booktsinsert', [
'uses' => 'BookSeatController#booktsinsert',
'as' => 'booktsinsert'
]);
Route::get('paywithpaypal', array('as' => 'addmoney.paywithpaypal','uses' => 'AddMoneyController#payWithPaypal',));

try
return redirect('paywithpaypal')->with("date", $date);
instead of this
return view('paywithpaypal', ['date' => $date]);
I hope this will help...

Data passed using with is stored into the session. So to access it, use the following:
{{ session('date') }}
Source

You have to use session method to fetch the data. below code redirecting to the dashboard page with staus.
return redirect('dashboard')->with('status', 'Profile updated!');
Retrieve this status from session method.
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif

Related

update checkbox value in laravel 8 (blade/ controller )

I'm beginner in laravel and I want to update multiple checkboxes in database ..
when I click at update button automatically my inputs show old value also my permissions are checked by old value to update it ..
relation between user and permission is manytomany .. I have another table named userpermissions who has id_user and id_permission
this is my update form in ( edit.blade.php)
<form action="{{ url('users/'.$user->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" id="name" required class="form-control" value="{{ $user->name }}">
#error('name')
<ul class="alert"><li class="text-danger">{{ $message }}</li></ul>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Email</label>
<input type="email" name="email" id="email" required class="form-control" value="{{ $user->email }}">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
#foreach($permissions as $permission)
<input type="checkbox" name="data[]" value="{{ $permission->id }}"
<?php if( in_array($permission->id, $user->userPermissions->pluck('permission_id')->toArray())){ echo 'checked="checked"'; } ?>/>
{{ $permission->name }}
#if($loop->iteration % 3 == 0 ) <br> #else #endif
#endforeach
</div>
</div>
</div>
<div class="text-right mt-4">
<button type="submit" class="btn btn-primary"> Add</button>
</div>
</form>
and this is my controller where I think have a problem with methods :
edit function
public function edit(User $user)
{
$permissions = Permission::get();
return view('users.edit', compact('user','permissions'));
}
update function :
public function update(UserRequest $request,User $user)
{
$user->update(
$request->only('name', 'email')
);
$user->userPermissions()->save($request->input('data'));
return redirect()->back()->with('status','user updated !');
}
and this is my functio store :
public function store(UserRequest $request)
{
$this->validate($request, [
'name' => 'required',
'email'=>'required|email',
'password' => 'required|confirmed|min:6',
]);
$user = User::create(
$request->only('name', 'email', 'password')
);
$user->userPermissions()->createMany($request->input('data'));
return redirect()->back()->with('status','Utilisateur ajouté !');
}
Thanks for advance !
$user->userPermissions()->save($request->input('data'));
One important thing to understand here, is that save() on relation doesn't remove old values from pivot table, it just add more values to it(no distinction check). You need something like refresh functionality. Look at attaching\detaching or sync, second one is more convenient.
In first case before saving permissions you can do this
// remove all old permissions
$user->userPermissions()->detach();
// update them with new one
$user->userPermissions()->attach($request->input('data'));
In second case, which is less verbose then first one you just need to pass and array of permissions to user object.
// this will do both things which we did before
$user->userPermissions()->sync($request->input('data'))
But i encourage you to read the docs and ask questions after ;)
Another thing which i saw and its not related to the current topic is
$user->userPermissions->pluck('permission_id')->toArray()
you are using lazy load inside of foreach loop which means that on each iteration of the loop you are making a query to the database(N + 1 problem). You can preload/eager load userPermissions instead of loading them on a fly by declaring with relation in your User model like this
class User extends Model
{
/**
* The relationships that should always be loaded.
*
* #var array
*/
protected $with = ['userPermissions'];
...
}
and then in your User object will have userPermissions property which you can compare to permissions.
Hope that you get main idea and info was useful for you!

How to solve the problem of getting unusual id in laravel

Here is my routes
Route::get('add-members/{id}','MemberController#create');
Route::post('save-member/{id}','MemberController#store');
This is my code to show the create form
public function create($id)
{
$team=Team::find($id);
$users = User::doesntHave('teams')->whereHas('roles', function($role) {
$role->where('name', 'member');
})->get();
return view('members.create',compact('users','team'));
}
An this is my code to store it
public function store(Request $request,$id)
{
$team=Team::find($id);
dd($request->id);
$team->users()->attach($request->id);
return redirect('home');
}
and this is my blade file
#extends('layouts.app')
#section('content')
<form action="{{url('save-member',$team->id)}}" method="post" accept-charset="utf-8">
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Select Member/s') }}</label>
<div class="col-md-6">
#foreach($users as $key => $user)
<input type="checkbox" name="id[]" value="{{$user->id}}">{{$user->email}}<br>
#endforeach
#error('member_id')
<span class="invalid-feedback" role="alert"><strong><font
color="red">{{ $message }}</font></strong></span>
#enderror
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
#endsection
Now when i select none of the user and just click save button it will save the the user id as 1. After i am doing dd($request->id) it will show me the output 1. But in my form there is no users left or my form is empty.So where from 1 is coming. you can see this picture for clearify.
Please help me to solve this problems
You should be more specific with what data you are requesting from the Request:
$request->id; // could be an input named 'id' or a route parameter named 'id'
$request->input('id'); // is an input
$request->route('id'); // is a route parameter
You are running into a situation where you have a route parameter named id and potentially an input named id. Using the dynamic property of the Request, $request->id, will return the input id if it is there, if not it falls back to returning a route parameter named id.
Here is an article from the past that shows the issue with not being specific about what you are trying to get from the Request object:
asklagbox - blog - watch out for request

how to redirect and show error validateion in laravel

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

Parameter goes into array as the name of the field instead of the value

What am I trying to achieve?
I have "tasks" and each task can have multiple "notes", so when you select a Task and click notes, it takes you to a page with all the notes for the task in which you clicked.
Each note has a field called "task_id", so my problem is passing this task_id to the note.
I'm trying to pass it like this on the notes form:
<form method="POST" action="{{route('notes.store',$task)}}">
#include('notes.form')
</form>
And it goes into my controller
public function store(Request $r)
{
$validatedData = $r->validate([
'note' => 'required',
]);
$r['created_by'] = Auth::user()->user_id;
return $r;
/*
$note = Note::create($r->all());
return redirect('/notes')->with('store');
*/
}
But I return it to see how its going and I get this:
{"_token":"OmGrbYeQDl35oRnmewrVraCT0SHMC16wE4gD56nl","note":"363","created_by":4,"8":null}
That 8 at the end is actually the correct task id, but it appears as the name instead of the value.
What may be causing this?
This is my form view:
#csrf
<div class="col">
<div class="form-group">
<input type="text" class="form-control" name="note">
</div>
</div>
<div class="col-10">
<div class="form-group">
<button class="btn btn-success" type="submit">Add note</button>
<br><br>
</div>
</div>
These are my routes:
Route::get('/tasks/{task}/notes', ['as' => 'tasks.notes', 'uses' => 'NoteController#index']);
Route::get('/projects/{project}/tasks', ['as' => 'projects.tasks', 'uses' => 'ProjectController#seeTasks']);
Route::get('/projects/results','ProjectController#filter');
Route::get('/tasks/results','TaskController#filter');
Route::resource('projects','ProjectController');
Route::resource('clients','ClientController');
Route::resource('tasks','TaskController');
Route::resource('users','UserController');
Route::resource('notes','NoteController');
You are trying to pass the task_id as a route parameter, but your notes.store route has no route parameters.
Verb Path Action Route Name
POST /notes store notes.store
Adding the task_id as a hidden input should properly send it with the request:
<form method="POST" action="{{ route('notes.store') }}">
<input type="hidden" name="task_id" value="{{ $task->id }}">
#include('notes.form')
</form>

Laravel : How to send variable from one page to another in blade

I'm building a laravel application where from The first page I want to send a variable or say value to second page in a form ..How do I do it?
Let's say In my first page I have several buttons so when a user click on any one button, he will be redirected to another page where he has to submit a form.
In first page while he select a button, he automatically select a course_id which will also submit inside the second page form. But How do i send the course_id from the first page button?
<li> A </li>
<li> <a href="{{route('registration')}}" >B</a> </li>
When a user click on the button second page will appear ..Where I'm gonna submit a form where course_id will come from the first page means the <a> tag
Here is my form demo:
{!! Form::open(array('route' => 'postRegistration','class'=>'form-horizontal','method'=>'POST')) !!}
{!! Form::token(); !!}
{!! csrf_field() ; !!}
<div class="form-group">
<label class="sr-only" for="form-first-name">Name</label>
<input type="text" name="name" placeholder="Name..." class="form-first-name form-control" id="form-first-name">
</div>
<div class="form-group">
<label class="sr-only" for="form-email">Email</label>
<input type="text" name="email" placeholder="Email..." class="form-email form-control" id="form-email">
</div>
<div class="form-group">
<label class="sr-only" for="form-last-name">Address</label>
<textarea rows="4" style="height:100px;" name="address" placeholder="Address..." class="form-last-name form-control" id="form-last-name"></textarea>
</div>
<button type="submit" class="btn">Submit</button>
{!! Form::close() !!}
In my database I have to submit the above field as well as the course_id from the database.
How do I do it in Laravel?
Any suggestion or solution please?
You can send the variable as route parameter. To do this change your <a> tags like this.
<li> A </li>
<li> B </li>
Then you need to allow your registration route to take parameter. Suppose your route is like this
Route::get('/registration', [
'as' => 'registration', 'uses' => 'SomeController#method'
]);
Change it to
Route::get('/registration/{course_id}', [
'as' => 'registration', 'uses' => 'SomeController#method'
]);
Now you have to add this parameter into your SomeController#method
public method($course_id){ ... }
Now pass this $course_id to your form view. To submit this variable with your other fields you can add this as hidden input field.
<div class="form-group">
<input type="hidden" name="course_id" value="{{ $course_id }}">
</div>
So you want to create page with multiple course links and each link redirects to registration page with the course id to be used in the registration form.
Your a href link should look like this
{!! link_to_route('registration',
$title = 'Course 1', $parameters = ['1'], $attributes =
['class'=>'btn btn-success']) !!}
Routes file web.php
Route::get('/registration/{course_id}','
CourseRegistration#showForm')->name('registration');
CourseController CourseController
public function showForm($course_id){
return view('registration')->with('courseid',$course_id);
}
Now you can access the course id with $courseid in view. If you want to pass it in form create a hidden or input tag with the data.
According to me, you're looking for a type of web app in which when a user submits a form the page opens up with the registered user details.
This can be done in Laravel like this:
routes.php
// For submitting form on this route
Route::post('users/register', 'UsersController#create')->name('users.register');
// For showing user's profile via user's id
Route::get('users/{id}/profile', 'UsersController#show')->name('users.profile');
UsersController.php
class UsersController {
public function create() {
$inputs = request()->all();
// Use Eloquent to save user info to DB and fetch insert id from DB...
return redirect()->route('users.profile', array('id' => $insert_id));
// Will open registered user profile page
}
public function show($id) {
$user = User::find($id);
if(!$user) {
abort('404');
}
return view('users/profile', compact('user'));
// At the users/profile.php page you can use $user variable to populate user's info
}
}
Usage of route method with passing data with route in Blade
{{ route('users.profile', array('id' => $user->id)) }}
For more help, see this >>
Hope this helps you!

Categories