Use input from one view to print result into another view - php

I want to use input from a form in one view and print results into another view. I get the following error: Undefined variable: users Thanks in advance!
The form (in a view called 'dashboard') that I am using to get email address:
...
<div class="search">
<header><h3>Search Friend</h3></header>
<form action="{{ route('search.friend') }}" method="post">
<div class="form-group">
<input class="form-control" type="text" name="email" id="email" placeholder="Friend's email">
</div>
<button type="submit" class="btn btn-primary">Post</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
</div>
...
The route to send data from 'dashboard' to Controller:
Route::post('/searchfriend',[
'uses' => 'FriendController#getSearchFriend',
'as' => 'search.friend',
'middleware' => 'auth'
]);
The controller where I use the email to find user:
class FriendController extends Controller
{
public function getSearchFriend(Request $request)
{
$this->validate($request,[
'email' => 'required | email'
]);
$email = $request['email'];
$users = User::where('email',$email)->get();
return view('userlist',['$users' => $users]);
}
}
The route to send the result to a 'userlist' view:
Route::get('/userlist',[
'uses' => 'FriendController#getSearchFriend',
'as' => 'userlist',
'middleware' => 'auth'
]);
Finally, the 'userlist' view:
#extends('layouts.master')
#section('title')
Users
#endsection
#section('content')
<section class="row new-post">
<div class="col-md-6 col-md-offset-3">
<header><h3>Users</h3></header>
<div class="userlist">
<header><h2>Click to Add Friend</h2></header>
#foreach($users as $user)
Name: {{ $user->username }}
#endforeach
</div>
</div>
</section>
#endsection

Change:
class FriendController extends Controller
{
public function getSearchFriend(Request $request)
{
$this->validate($request,[
'email' => 'required | email'
]);
$email = $request['email'];
$users = User::where('email',$email)->get();
return view('userlist',['$users' => $users]);
}
}
to:
class FriendController extends Controller
{
public function getSearchFriend(Request $request)
{
$this->validate($request,[
'email' => 'required | email'
]);
$email = $request['email'];
$users = User::where('email',$email)->get();
return view('userlist',['users' => $users]);
}
}
You don't need the $ when passing the name of the variable to the view.

#Ryan J Field is correct. Also, you can pass the variable in many different ways. Such as -
return view('userlist')->with('users', $users);
Or,
return view('userlist', compact(users));

Related

How do I redirect to another page after form submission in Laravel

form
When i submit the form it redirects back to the form itself, can anyone help me?
<form action="/jisajili" method="POST">
#csrf
<div class="card-panel z-depth-5">
<h5 class="center red-text">Jiunge Nasi</h5>
<div class="input-field">
<i class="material-icons prefix">account_circle</i>
<input type="text" name="username" class="validate">
<label>Jina lako</label>
</div>
<div class="input-field">
<i class="material-icons prefix">phone</i>
<input type="number" name="phone" class="validate">
<label>Nambari ya simu</label>
</div>
....
</p>
<input type="submit" name="submit" value="Jiunge" class="btn left col s12 red">
Controller
class registration extends Controller{
public function create(){
return view('jisajili.jiunge');
}
public function store(Request $request){
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$cpassword = $request -> input('cpassword');
$reg->save();
$validated = $request->validate([
'name' => 'required|unique:posts|max:10',
'body' => 'required',
]);
return redirect('home');
}
}
What I would do is first check for the data requirements before you add the object to the database. Also I would add the columns of the models into the Model file to use the Object::create function with an array parameter.
I recomment to use routing in your blade file. I noticed you used action="/route". What you want to do is naming your routes with ->name('route_name') in the route files. To use them in your blade files with the global route function route="{{ route('route_name') }}".
<?php
class PostController extends Controller
{
public function index()
{
return view('post.create');
}
public function store(\Illuminate\Http\Request $request)
{
$validator = Validator::make(
$request->all(),
[
'name' => 'required|unique:posts|max:10',
'body' => 'required'
]
);
// Go back with errors when errors found
if ($validator->fails()) {
redirect()->back()->with($validator);
}
Post::create(
[
'name' => $request->get('name'),
'body' => $request->get('body')
]
);
return redirect()
->to(route('home'))
->with('message', 'The post has been added successfully!');
}
}
What you can do after this is adding custom errors into the controller or add them into your blade file. You can find more about this in the documentation of Laravel.
it redirects you back because of validation error.
change password confirmation name from cpassword into password_confirmation as mentioned in laravel docs
https://laravel.com/docs/7.x/validation#rule-confirmed
update your controller into:
public function store(Request $request){
$validated = $request->validate([
'username' => 'required',
'phone' => 'required',
'email' => 'required',
'password' => 'required|confirmed'
]);
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$reg->save();
return redirect('home');
}
in your blade add the following to display validation errors:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Passing Data through Return Redirect Back to Update Request

I am trying to allow a user to update their information after they have submitted a form, but did not check a certain box. Everything is within the same page and I am controlling the different modals by returning a message, which triggers a script to open the different modals.
For some reason, I can't seem to pass the ID or email through to the next step. Can anyone help with this?
Whenever, I try, I get the following error:
Undefined variable: leads
Any idea?
Thanks!!!
Files:
web.php
index.blade.php
LeadsController.php
Leads.php
Web.php
Route::post('/', [
'uses' => 'LeadsController#store',
'as' => 'leads.store'
]);
Route::patch('/{email}', [
'uses' => 'LeadsController#update',
'as' => 'leads.update'
]);
Index.blade.php
<html>
<div id="contact" class="modal fade">
<div class="modal-dialog modal-content modal-lg">
<div class="modal-body">
<form id="form" class="form" action="/" method="post" accept-charset="utf-8">
{{ csrf_field() }}
<input type="email" name="email" value="{{ old('email') }}">
<input type="checkbox" name="newsletter">
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
#if(session()->has('message'))
<div id="sign_up" class="modal fade">
<div class="modal-dialog modal-content modal-lg">
<div class="modal-body">
<form method="post" action="{{ route('leads.update', $leads->email) }}">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<input type="checkbox" name="newsletter">
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
#endif
</body>
</html>
LeadsController.php
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput($request->all);
} else {
try {
$leads = new Leads;
$leads->email = $request->email;
$leads->newsletter = $request->newsletter;
$leads->save();
if($request->newsletter == ''){
return redirect()->back()->with('message','sign up')->withInput($request->all)->with($leads->email, $request->get('email'));
}
if($request->newsletter == 'true'){
return redirect()->back()->with('success','success');
}
} catch (Exception $e) {
return response()->json(
[
'status' => false,
'error' => base64_encode($e->getMessage()),
],
Status::HTTP_INTERNAL_SERVER_ERROR
);
}
}
}
public function update($email)
{
$leads = Leads::find($email);
$leads->newsletter = $input('newsletter');
$leads->save();
return redirect()->back()->with('success','success');
}
Leads.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Leads extends Model
{
protected $table = 'my_renamed_table';
public $timestamps = false;
protected $fillable = ['email', 'newsletter'];
}
Thanks for all of your help and your questions! You helped push me in the right direction.
Here is how I solved it:
I had to correct myself in how I pushed the $email through to the view:
LeadsController
return redirect()
->back()
->with('message','sign up')
->withInput($request->all)
->with('email', $request->get('email'));
Notice how I'm sending the email through as 'email' here.
Then, I pushed the email through the view in the 2nd form like this:
index
<form method="post" action="{{ route('leads.update', session('email')) }}">
Then, finally, in order to capture the email again, use it to find the lead that I wanted, I had to drastically change the update:
public function update($email)
{
DB::table('my_renamed_table')
->where('email', $email)
->update(['newsletter' => Input::get('newsletter')]);
return redirect()->back()->with('success','success');
}
Thanks again!

Laravel redirect() to is not generating the correct url

I would like to start by apologizing for the newbish question.
I'm in the process of making a simple CRUD controller on Laravel.
My create method is as follows:
public function create(Request $request)
{
$dummy = new Dummy();
$dummy->title = $request->title;
$dummy->content = $request->dummy_content;
$dummy->created_at = new \DateTime();
$dummy->updated_at = new \DateTime();
$dummy->save();
return redirect()
->route('index/view/', ['id' => $dummy->id])
->with('message', 'Dummy created successfully');
}
my view method:
public function view($id)
{
$dummy = Dummy::find($id);
return view('index/view', [
'dummy' => $dummy
]);
}
my corresponding routes:
Route::get('index/view/{id}', 'IndexController#view');
Route::post('index/create', 'IndexController#create');
and my form:
<form action="create" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="dummy_content" cols="80" rows="5" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-default btn-sm">Submit</button>
</form>
When I submit my form I get the following exception:
InvalidArgumentException in UrlGenerator.php line 314:
Route [index/view/] not defined.
I've been stuck here for quite some time and I still can't figure out why I'm not generating my route properly.
What am I missing?
You are trying to call a route when instead you should call the controller. This will do the trick
return redirect()->action('IndexController#view', ['id' => $id])->with($stuff);
Also, i suggest you to define aliases to routes, so you could do something like
In your controller:
return Redirect::route('route_alias', ['id' => $id])->with($stuff);
In your routes:
Route::get('/index/view/{id}', [
'as' => 'route_alias',
'uses' => 'IndexController#view'
]);

Laravel NotFoundHttpException in RouteCollection.php line 161:

I'm having a hard time on this error when I encounter this error, My solution is to create new project. I know this question is alway ask here. I followed all tutorial line by line and is always error.
Sign Up:
#extends('layouts.master')
#section('content')
<div class="col-md-6">
<form method="POST" action="{{ route('signup') }}">
<div class="form-group">
<input type="text" name="username" placeholder="Username" class="form-control"></input>
</div>
<div class="form-group">
<input type="password" name="password" placeholder="Password" class="form-control"></input>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary pull-right"></input>
<input type="hidden" name="_token" value="{{ Session::token() }}"></input>
</div>
</form>
</div>
#endsection
routes.php
<?php
Route::get('/', function () {
return view('welcome');
});
Route::post('/signup', [
'uses' => 'UserController#postSignUp',
'as' => 'signup'
]);
UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class UserController extends Controller
{
public function postSignUp(Request $request){
$username = $request['username'];
$password = bcrypt($request['password']);
$user = new User();
$user->username = $username;
$user->password = $password;
$user->save();
return redirect()->back();
}
}
I don't see a get route for your form. Your post route will work only if you submit the form.
So, in your routes.php, there should something like
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/signup', [
'uses' => 'UserController#getSignUp',
'as' => 'signup'
]);
Route::post('/signup', [
'uses' => 'UserController#postSignUp',
'as' => 'signup'
]);
And, in UserController#getSignUp you just load the view of the form.
//your blade file is OK ,you can use same
//you route
Route::get('/signup', function () { //route1 to view form
return view('signUp');
});
Route::post('/signup', [ // route2 to handle form request
'uses' => 'UserController#postSignUp',
'as' => 'signup'
]);
to view your form you have to use get method which is route1 ,after submitting the form your postSignUp method will redirect to get route which is route1.
//your controller
public function postSignUp(Request $request){
$username = $request->username; //to access username
$password = bcrypt($request->password); //to access password
$user = new User();
$user->name = $username;
$user->password = $password;
$user->save();
return redirect()->back();
}
in your blade file you use name filed as username and password for user's username and password respectively.so In user Usercontroller you can directly access them as $request->username and $request->password for User's username and password respectively.

var $errors in the view with the laravel framework

i use the validated method for validate request, but the var errors is empty in the view :/.
in the controller, i have:
Route::group(['middleware' => ['web']], function () {
Route::get('/', function(){
return view('home');
})->name('home');
Route::group(['prefix' => 'do'], function($name = null){
Route::get('/{action}/{name?}', ['uses' => 'controllers#get', 'as' => 'get']);
Route::post('/', ['uses' => 'controllers#post', 'as' => 'post' ]);
});
});
for the controller, i have:
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class controllers extends Controller
{
public function get($action, $name=null)
{
return view('actions.' . $action, ['name' => $name]);
}
public function post(Request $request)
{
$this->validate($request, [
'action' => 'required',
'name' => 'alpha|required'
]);
return view('actions.'.$request['action'] , ['action' => $request['action'], 'name'=>$this->transformName($request['name'])]);
}
private function transformName($name)
{
$add = "king ";
return $add.strtoupper($name);
}
}
and for the view, i have:
#extends('layouts.master')
#section('content')
<div class="centered">
greet
hug
kiss
<br >
<br >
#if (isset($errors) && count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
{!! $errors->first() !!}
#endforeach
</ul>
</div>
#endif
<form action="{{ route('post')}}" method="post">
<label for="select-action">I want to...</label>
<select id="select-action" name="action">
<option value="greet">greet</option>
<option value="hug">hug</option>
<option value="kiss">kiss</option>
</select>
<input type="text" name="name">
<button type="submit">action</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
</form>
</div>
#endsection
if i delete the middleware of the route, the var errors work correctly.
how i can fix this?
thanks.
If you're using latest Laravel 5.2 build, you should remove web middleware from routes. Now it applies automatically to all routes and if you're trying to add it manually, it causes different errors.

Categories