Undefined variable $credentials, tried several solutions but couldn't understand my mistake - php

I'm a beginner, learning Laravel. I was trying to create a web page which will show me my login Info(like email and password) once I log in. In my controller part I passed values using route parameter, but when I call it in blade, it shows
ErrorException
Undefined variable $credentials (View: .....\new project\NewLearn\resources\views\welcome.blade.php)
My database has users table( email and password columns (which will be shown only), along with name,id, timestamps).
my LoginController
public function loginProcess(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:4',
]);
$credentials = $request->except(['_token']);
if (auth()->attempt($credentials)) {
return redirect()->route('welcome', [$credentials->email]);
}
else{
$this->setErrorMessage('Invalid!');
return redirect()->back();
}
my routes
Route::get('/', function () {
return view('login');});
Route::view('/welcome', 'welcome')->middleware('auth')->name('welcome');
Route::post('/login', [App\Http\Controllers\LoginController::class, 'loginProcess'])->middleware('guest')->name('login');
Route::get('/login', [App\Http\Controllers\LoginController::class, 'loginProcess'])->middleware('guest');
my welcome.blade.php
#extends('master')
#section('contents')
#include('partials.jumbotron')
#stop
#section('content')
<h3 class="pb-3 mb-4 font-italic border-bottom">
{{$credentials->email}}
</h3>
<div class="blog-post">
<h2 class="blog-post-title">Sample blog post</h2>
</div>
<nav class="blog-pagination">
<a class="btn btn-outline-primary" href="#">Older</a>
<a class="btn btn-outline-secondary disabled" href="#">Newer</a>
</nav>
#stop
Where am I making the mistake? Thanks in advance.

You are making it pretty hard on yourself.
Let us start by changing
Route::view('/welcome', 'welcome')->middleware('auth')->name('welcome');
to
Route::get('/welcome', function() {
$user = auth()->user();
return view('welcome', compact('user'));
})->middleware('auth')->name('welcome');
Now in login process simply change
if (auth()->attempt($credentials)) {
return redirect()->route('welcome', [$credentials->email]);
}
to
if (auth()->attempt($credentials)) {
return redirect()->route('welcome');
}
Now inside your blade file you can simple use
{{ $user->email }}

You already pass $credentials->email from controller. If you want to keep your blade (view) file you can just pass $credentials from controller and return view with parameters instead of route redirect.
Something like this:
return view('welcome', [
'credentials' => $credentials,
])

Related

How to fix MethodNotAllowedHttpException error in Laravel 5.7?

I added a CRUD interface for my user's table, and instead of a delete button, I used a block button. Which blocks a user (sets bloque field in the database from 0 to 1). I added a new function in my controller called block which is supposed to do the job yet I get a MethodNotAllowedHttpException error every time I click the blocking button.
UserController
public function block($id)
{
$user = User::find($id);
$user->bloque = 1;
$user->save();
return redirect('/users')->with('success', 'Utilisateur bloqué');
}
The blocking HTML fragment
<form action="{{ route('users.block', $user->id)}}" method="get">
#csrf
<!-- #method('DELETE')-->
<button class="btn btn-danger" type="submit">Bloquer</button>
</form>
Routes
Route::get('/block', [
'uses' => 'UserController#block',
'as' => 'users.block'
]);
I think the problem is related to id value, It should be instantiated from $request object. Like:
public function block(Request $request)
{
$user = User::find($request->id);
$user->bloque = 1;
$user->save();
return redirect('/users')->with('success', 'Utilisateur bloqué');
}

#include a view with controller functionality - Laravel 5.4

I am working on a profile page for my web application. Within this view profile.blade.php I would like to include the view progress/index.blade.php. I have the following structure:
profile.blade.php
<div class="panel panel-default">
<div class="panel-heading clearfix">
<h1 class="panel-title pull-left">{{ $user->name }} Progress</h1>
</div>
<div class="panel-body">
#include('client.progress.index')
</div>
</div>
web.php
Route::group(['middleware' => ['auth', 'client'], 'prefix' => 'client', 'as' => 'client.'], function () {
Route::get('home', 'Client\HomeController#index')->name('home');
Route::get('profile', 'Client\UserController#profile')->name('profile');
Route::get('progress', 'Client\UserController#progress')->name('progress.index');
});
UserController#progress
public function progress(){
$auth = Auth::user();
$progressPictures = Picture::select('*')
->where('user_id', $auth->id)
->get();
return view('client.progress.index', ['progressPictures' => $progressPictures]);
}
client.progress.index
<p>Progress pictures</p>
#foreach($progressPictures as $progressPicture)
<img src="/storage/uploads/progress/{{ $progressPicture }}" style="width:150px; height:150px; float:left; border-radius:50%; margin-right:25px;">
#endforeach
When I remove the php part from the index.blade.php, the site works. but when i add the foreach loop, $progressPictures is undefined. I am not calling the UserController#progress in some way. Could some one help me with this?
Generally based on my observation, the variable is not making it to the views because you are routing to another while the other view is handled by another controller.
One of the ways you can do that is either to have a trait where you can easily reuse the result of getting progressPictures or because you quickly need it, you might have to duplicate this code as well in the profile method in your UserController so that you can have the progressPictures also in profile page:
So you'll have:
public function profile()
{
//codes before or after
$auth = Auth::user();
$progressPictures = Picture::select('*')
->where('user_id', $auth->id)
->get();
//......
return view('profile', compact('progressPictures'));
Ps: unnecessary code repetition is not generally recommended, but I would do this first then clean up things after.
Change this to
return view('client.progress.index', ['progressPictures' => $progressPictures]);
to this
return view('client.progress.index')-> with('progressPictures', $progressPictures);
Change
#include('client.progress.index')
to
#include('client.progress.index', ['progressPictures' => $progressPictures])

Laravel undefined variable in view

I'm new to laravel. Using version 5.3 and tried to search but don't see what I'm doing wrong. I keep getting an "Undefined variable: user" in my view. I'm also doing form model binding. Model binding works properly when manually entering URL. Just can't click on link to bring up edit view.
My routes:
Route::get('/profile/edit/{id}', 'ProfileController#getEdit');
Route::post('/profile/edit/{id}', 'ProfileController#postEdit');
My controller:
public function getEdit($id){
$user= User::findOrFail($id);
return view('profile.edit', compact('user'));
}
My view:
<li>Update profile</li>
My form:
{!! Form::model($user,['method' => 'POST', 'action'=> ['ProfileController#postEdit', $user->id]]) !!}
public function getEdit($id){
$user= User::findOrFail($id);
return view('profile.edit', ['user' => $user]);
}
public function postEdit($id){
$user= User::findOrFail($id);
return view('profile.edit', ['user' => $user]);
}
Try this for pass data array in view
public function getEdit($id){
$data['user'] = User::findOrFail($id);
return view('profile.edit')->withdata($data);
}
in view page try to print $data
{{ print_r($data) }}
Please edit your getEdit method
public function getEdit($id){
$user= User::findOrFail($id);
dd($user);
return view('profile.edit', compact('user'));
}
check if there is any data user variable.
In my opinion, the statement in your view
<li>Update profile</li>
is causing the issue. You may confirm this by looking at the URL in the address bar after clicking on the Update profile link.
Try changing it to this
<li>Update profile</li>

Laravel 5.2 Displaying Validation Error

I am trying to validate a simple form by using Laravel's validator. Looks like validation works fine but i am unable to display errors. Form and controller looks like this.
Form
<h3>Add a New Team</h3>
<form method="POST" action="/teams">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<input class="form-control" name="team_name" value="{{ old('team_name') }}" />
</div>
<div class="form-group">
<button type="submit" class="btn bg-primary">Add Team</button>
</div>
</form>
#if(count($errors))
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Controller Method
public function store(Request $request) {
$this->validate($request, [
'team_name' => 'required|min:10'
]);
$team = new Team;
$team->team_name = $request->team_name;
$team->save();
return back();
}
If i remove web middleware group from my routes, errors displays fine.
Currently my routes.php file looks like this
Route::group(['middleware' => ['web']], function () {
Route::get('/teams', 'TeamsController#create');
Route::post('/teams', 'TeamsController#store');
});
How do i fix this problem ? Any help would be appreciated.
why do use the validation looks like laravel 4 while you are using laravel 5!!
in laravel 5 you need first to make Request class that handle your validation
php artisan make:request RequestName
you will find the request class that you make in
'app/http/Requests/RequestName.php'
and in the rules function you can handle your validation
public function rules()
{
return [
// put your validation rules here
'team_name' => 'required|min:10'
];
}
finally in your controller
use App\Http\Requests\RequestName;
public function store(RequestName $request) {
Team::create($request->all());
return Redirect::back();
}
for more illustration here
I recommend you to use Laravel Form Request
run
artisan make:request TeamRequest
add some logic and rules
class TeamRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true; //you can put here any other variable or condition
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
// put your validation rules here
];
}
}
then your contorller code will be like so:
public function store(TeamRequest $request)
{
$team = Team::create($request->all());
return back();
}
you no longer need to validate request and redirect back with errors and other stuff, laravel will do it for you
And you code looks more clean and neat, isn't it?
Write below code in your controller :
// define rules
$rules = array(
'team_name' => 'required|min:10'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
// something
return Redirect::back()
->withErrors($validator) // send back all errors to the login form
->withInput();
}
else
{
// something
// save your data
$team = new Team;
$team->team_name = $request->team_name;
$team->save();
}
change in View File :
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
After a little bit research, i have found that Laravel 5.2 has a RouteServiceProvider and it includes web middleware group for all routes. So i do not have to add the web middleware group to my routes manually. I just removed it from routes.php and problem solved.
If i remove web middleware group from my routes, errors displays fine.
In Laravel 5.2 the web midddleware is automatically applied to your routes in routes.php so no need to apply web middleware again. It is defined in mapWebRoutes() method of RouteServiceProvider.

Upon seemingly correct routing getting error Route not defined! - Laravel 4

I'm developing a very basic application using Laravel 4.1 where users can signup and ask question, pretty basic stuffs. I'm now a bit confused about the restful method which would look something like this public $restful = true in laravel 3. Since then laravel has changed a lot and I got stucked with the restful idea. So I decided to leave it and go on developing the skeleton of my application. Everything went well until I created the postCreate method in my homeController to let authorized users submit their question through a form. I believe I routed the method correctly and the index.blade.php view is alright as well. I just can't figure out why I'm getting this following error even though the codes seem to be okay.
Route [ask] not defined. (View: C:\wamp\www\snappy\app\views\questions\index.blade.php)
If you have got what I'm doing wrong here would appreciate if you point it out with a little explanation.
I'm totally new in laravel 4 though had a bit of experience in the previous version.
Here's what I have in the HomeController.php
<?php
class HomeController extends BaseController {
public function __construct() {
$this->beforeFilter('auth', array('only' => array('postCreate')));
}
public function getIndex() {
return View::make('questions.index')
->with('title', 'Snappy Q&A-Home');
}
public function postCreate() {
$validator = Question::validate(Input::all());
if ( $validator->passes() ) {
$user = Question::create( array (
'question' => Input::get('question'),
'user_id' => Auth::user()->id
));
return Redirect::route('home')
->with('message', 'Your question has been posted!');
}
return Redirect::route('home')
->withErrors($validator)
->withInput();
}
}
this is what I have in the routes.php file
<?php
Route::get('/', array('as'=>'home', 'uses'=>'HomeController#getindex'));
Route::get('register', array('as'=>'register', 'uses'=>'UserController#getregister'));
Route::get('login', array('as'=>'login', 'uses'=>'UserController#getlogin'));
Route::get('logout', array('as'=>'logout', 'uses'=>'UserController#getlogout'));
Route::post('register', array('before'=>'csrf', 'uses'=>'UserController#postcreate'));
Route::post('login', array('before'=>'csrf', 'uses'=>'UserController#postlogin'));
Route::post('ask', array('before'=>'csrf', 'uses'=>'HomeController#postcreate')); //This is what causing the error
And finally in the views/questions/index.blade.php
#extends('master.master')
#section('content')
<div class="ask">
<h2>Ask your question</h2>
#if( Auth::check() )
#if( $errors->has() )
<p>The following erros has occured: </p>
<ul class="form-errors">
{{ $errors->first('question', '<li>:message</li>') }}
</ul>
#endif
{{ Form::open( array('route'=>'ask', 'method'=>'post')) }}
{{ Form::token() }}
{{ Form::label('question', 'Question') }}
{{ Form::text('question', Input::old('question')) }}
{{ Form::submit('Ask', array('class'=>'btn btn-success')) }}
{{ Form::close() }}
#endif
</div>
<!-- end ask -->
#stop
Please ask if you need any other instance of codes.
Your 'ask' route is not named. When you pass 'route' => 'foo' to Form::open, that assumes you have a route named 'foo'. add 'as' => 'ask' to your /ask route and it should work.
Alternatively, use URL or Action to resolve the form's target url instead:
Form::open(['url' => 'ask']);
Form::open(['action' => 'HomeController#postCreate']);
you are using name route ask in your form which is not exist. I have created the name route ask for you.
Route::post('ask', array('before'=>'csrf', 'as' => 'ask', 'uses'=>'HomeController#postcreate'));
{{ Form::open( array('route'=>'ask', 'method'=>'post')) }}
^^^^ -> name route `ask`
{{ Form::token() }}

Categories