I am trying to use a code from https://www.youtube.com/watch v=EM0Wdcux6AE&t=13s&ab_channel=SevenStac , which is very helpful. Although I can't make the updating password/email part.
Error: it shows an error $user is an undefined variable.
I have searched already, tried these:
Undefined variable: users
Undefined variable: user
but they're not applicable in my case because I'm using Laravel 9 with Firebase, firestore database.
I also tried doing:
php artisan cache:clear
php artisan route:clear
Disclaimer, most of these codes are copied from the youtube video. The login credentials, reset password in email, and register worked but not the updating part.
web.php:
Route::resource('/home/profile', App\Http\Controllers\Auth\ProfileController::class)->middleware('user','fireauth');
Note: This is the only line that I included because it is the only relevant part. You can ask if you want more.
settings.blade.php:
{!! Form::model($user, ['method'=>'PATCH', 'action'=> ['App\Http\Controllers\Auth\ProfileController#update',$user->uid]]) !!}
{!! Form::open() !!}
<div class="form-group px-3">
{!! Form::label('email', 'Email ',['class'=>'pt-3 col-12 text-left pl-0']) !!}
{!! Form::email('email', null, ['class'=>'col-md-8 form-control'])!!}
</div>
<div class="form-group px-3">
{!! Form::label('new_password', 'New Password:',['class'=>'col-12 text-left pl-0']) !!}
{!! Form::password('new_password', ['class'=>'col-md-8 form-control'])!!}
</div>
<div class="form-group px-3">
{!! Form::label('new_confirm_password', 'Confirm Password:',['class'=>'col-12 text-left pl-0']) !!}
{!! Form::password('new_confirm_password', ['class'=>'col-md-8 form-control'])!!}
</div>
{!! Form::submit('Save', ['class'=>'btn btn-primary']) !!}
{!! Form::close() !!}
ProfileController.php:
public function index()
{
//
$uid = Session::get('uid');
$user = app('firebase.auth')->getUser($uid);
return view('admin.settings',compact('user'));
}
public function update(Request $request, $id)
{
//
$auth = app('firebase.auth');
$user = $auth->getUser($id);
try {
if ($request->new_password == '' && $request->new_confirm_password =='') {
$request->validate([
'displayName' => 'required|min:3|max:12',
'email' =>'required',
]);
$properties =[
'displayName' => $request->displayName,
'email' => $request->email,
];
$updatedUser = $auth->updateUser($id, $properties);
if ($user->email != $request->email) {
$auth->updateUser($id, ['emailVerified'=>false]);
}
Session::flash('message', 'Profile Updated');
return back()->withInput();
} else {
$request->validate([
'new_password' => 'required|max:18|min:8',
'new_confirm_password' => 'same:new_password',
]);
$updatedUser = $auth->changeUserPassword($id, $request->new_password);
Session::flash('message', 'Password Updated');
return back()->withInput();
}
return $input;
} catch (\Exception $e) {
Session::flash('error', $e->getMessage());
return back()->withInput();
}
Note: in "return $input" it shows an error also, that it is an undefined variable. However, it still worked before when I tried. But when I tried to incorporate my UI with these codes, it did not anymore.
General note: you may be confused that I am using ProfileController with my settings blade, it is because I don't want to move any codes first into my SettingsController, I'm still trying to make it work. Also, it worked before, now it did not.
Related
i want to update status user just pass parameter of 'status'.
this is my code, but i don't know, why i can not update user status. how to fix this problem?
my controller
public function activation()
{
// dd('test');
$action = Input::get('status');
if (Input::get('activate'))
{
$this->activateUser($action);
}
elseif (Input::get('inactivate'))
{
$this->deactivateUser($action);
}
return redirect(route('admins-users.index'))->with('message-post', 'Status was updated successfully');
}
public function activateUser($user)
{
//dd('active');
User::findOrNew($user)->update(['status' => "1"]);
}
public function deactivateUser($user)
{
// dd('nonactive');
User::findOrNew($user)->update(['status' => "0"]);
}
my route
Route::post('admins-users/status', 'Backend\StatusController#activation');
my view
{!! Form::open(array('url' => 'admins-users/status')) !!}
#if ($user->status)
{!! Form::submit('inactivate', ['name' => 'inactivate', 'class'=>'btn btn-xs btn-default']) !!}
#else
{!! Form::submit('Activate', ['name' => 'activate', 'class'=>'btn btn-xs btn-success']) !!}
#endif
{!! Form::close() !!}
After trying several ways. finally, i was found the answer for this problem using Ajax and select option. i add hash id before pass to controller and decode again in controller. i thinks id that pass must be concerned.
my controller
public function control(Request $request){
$status = $request->status;
$iduser = $request->iduser;
$key = Hashids::connection('main')->decode($iduser)[0] ?? abort(404);
$update = User::where('id', $key)->update(['status'=> $status]);
if($update)
{
return redirect(route('admins-users.index'))->with('message-post', 'Status user was updated successfully');
}
}
my form
using hash id to encode id user
#php $parameter = Hashids::connection('main')->encode($user->id); #endphp
{!! Form::hidden(null,$parameter, ['id'=> 'iduser'.$parameter ])!!}
{!! Form::select(
'status',
array(1=>'Active',0=>'Not Active'),
$user->exists ? $user->status : null,
[
'id' => 'action'.$parameter,
'placeholder' => 'Choose a status'
]
)
!!}
script
$(document).ready(function(){
#foreach($users as $user)
#php $parameter = Hashids::connection('main')->encode($user->id); #endphp
$("#action{{ $parameter }}").change(function(){
var status = $("#action{{ $parameter }}").val();
var iduser = $("#iduser{{ $parameter }}").val();
if(status==""){
alert("Please select an option");
}
else{
if (confirm('Do you want to change {{ $user->name }} status to {{ $user->status ? 'InActive' : 'Active' }}?')) {
$.ajax({
url: '{{ url("/action") }}',
data: 'status=' + status + '&iduser=' + iduser,
type: 'get',
success:function(response){
console.log(response);
}
});
document.location.reload();
}
}
});
#endforeach
});
Try with this
{!! Form::open(['url' => 'admins-users/status', 'method' => 'get' !!}
<input type="hidden" name="user_id" value="{{ $user->id }}">
#if ($user->status)
{!! Form::submit('inactivate', ['name' => 'inactivate', 'class'=>'btn btn-xs btn-default']) !!}
#else
{!! Form::submit('Activate', ['name' => 'activate', 'class'=>'btn btn-xs btn-success']) !!}
#endif
{!! Form::close() !!}
Your route
Route::get('admins-users/status', 'Backend\StatusController#activation');
Your Controller Method
public function activation(Request $request)
{
$user_id = $request->user_id
if ($request->acticate) {
$this->activateUser($user_id);
}
elseif ($request->inactiavte) {
$this->deactivateUser($user_id);
}
return redirect(route('admins-users.index'))->with('message-post', 'Status was updated successfully');
}
Hope this helps :)
here you can see my form where I put in a username and have a hidden idgroup field.
{!! Form::open(array('route'=>'create.invitation')) !!}
<div class="form-group">
{{Form::label('username', 'Username')}}
{{Form::text('username', '', ['class' => 'form-control', 'placeholder' => 'Enter Username'])}}
<input type="hidden" name="idgroup" value="{{$group}}"/>
{{ csrf_field() }}
</div>
<div>
{{Form::submit('Submit',['class' => 'btn btn-primary'])}}
<a class="btn btn-default btn-close" href="{{ route('home') }}">Cancel</a>
</div>
{!! Form::close() !!}
After that this route leads me to my controller function
Route::post('invitation/show', 'InvitationController#create')->name('create.invitation');
How can I add the username and the idgroup to my url?
My problem is now when I click submit I get back this url http://127.0.0.1:8000/invitation/create and when I click enter to the url line I get an error no message because no parameter will pass to the function.
Add. Here is the function
public function create(Request $request)
{
$request->validate([
'username' => [
'required', 'alpha_num', new ExistingUser, new UserNotAdmin
]
]);
$username = $request->username;
$iduser = User::where('name', $username)->select('id')->first();
$group = $request->idgroup;
return view('invitation.overview')->with('group', $group)->with('iduser', $iduser);
}
You cannot pass parameter inside POST body without submitting a form.
But you can try to allow both GET or POST by using any() for the route, so you can test the page around.
Route::any('invitation/show', 'InvitationController#create')->name('create.invitation');
And then, you can try pass variable through queries inside URL
http://127.0.0.1:8000/invitation/create?username=something&idgroup=1
I am trying to run a search query on all of my comments. I am encountering a number of problems. I would to have two search queries one that runs a search on the comment ID and another that runs a search on the username that is connected to the comment through the user_id FK.
Currently im getting the problem:
Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in
Tables:
Comment- id, comment, user_id, timestamps
User - id, name, username
Models:
class Comment extends Model
{
public function author()
{
return $this->belongsTo('App\User','user_id');
}
}
Controller:
public function index(Request $request)
{
$comment =Comment::paginate(10);
$id=$request->input('id');
$name=$request->input('username');
if(!empty($id)){
$comment->where('id', $request->input('id') )->get();
}
if(!empty($name)){
$comment->where($comment->author->username, 'LIKE', '%'.$name.'%')->get();
}
return view('comments.index')->withComment($comment);
}
View:
<div class="panel-body">
{!! Form::open(['route' => 'comments.index', 'method' => 'GET']) !!}
<div class="col-md-5">
{!! Form::label('id', 'Search By ID:') !!}
{!! Form::text('id', null, array('class' => 'form-control')) !!}
</div>
<div class="col-md-5">
{!! Form::label('username', 'Search By Username:') !!}
{!! Form::text('username', null, array('class' => 'form-control')) !!}
</div>
<div class="col-md-2">
{!! Form::submit('Find Comments', array('class' => 'btn btn-send ')) !!}
</div>
{!!Form::close()!!}
</div>
#foreach($comment as $comments)
//data
#endforeach
The paginate function immediately executes the query for you, so you are using Collection functions after that. The get function on collections expects a key as a parameter, this is the problem.
To fix this, you can either remove the ->get() or use the paginate function at the end of your query as shown below.
$comment = Comment::query();
$id = $request->input('id');
$name = $request->input('username');
if (!empty($id)) {
$comment = $comment->where('id', $request->input('id'));
}
$result = $comment->paginate(10);
Since You have Paginated already
public function index(Request $request)
{
$comment = new Comment();
$id=$request->input('id');
$name=$request->input('username');
if(!empty($id)){
$comment->where('id', $request->input('id') )->get();
}
if(!empty($name)){
$comment->where($comment->author->username, 'LIKE', '%'.$name.'%');
}
return view('comments.index')->withComment($comment->paginate(10));
}
You cannot paginate and get it again, its like using SELECT statement twice on same object.
Missing required parameters for [Route: templates.answers.store] [URI: templates/{template}/answers]. (View: D:\Applications\xampp\htdocs\clientpad\resources\views\templates\answers.blade.php)
I am having the above error when I try and use a form with my foreach loop. I am not even sure why this is happening, maybe because I am new at Laravel. But this error goes away once I get rid of the AnswerController#store from the Eloquent form. It is possible I am doing this whole form wrong.
Here is what I want to do: A user made a template with questions, on the click of use button which goes to this url: http://clientpad.test/templates/{id}/answers they see their made questions which are shown with a foreach loop. Around it a Form is made so a user can answer the questions made. The form and answer field shows when I delete the action AnswerController#store, otherwise I get the above error.
Here is the code:
AnswerController:
public function index(Template $template, Question $question)
{
$questions = $template->questions->mapWithKeys(function($question){
return [$question->id => $question->question];
});
return view('templates.answers')->with('template', $template)->with('questions',$questions);
}
public function store(Request $request, Question $question, Answer $answer)
{
$answers = new Answer;
$answers->answer = $request->input('answer');
$answers->question_id = $request->input('question_id'); //current template id
$question->answers()->save($answers);
dd($question);
return redirect('/dashboard')->with('success', 'Your Question Was Successfully Created');
}
answers.blade.php
{!! Form::open(['action' => 'AnswersController#store', 'method' => 'POST']) !!}
#foreach ($questions as $question) <!-- Index counts the questions shown -->
<div class="panel panel-default">
<div class="panel-body">
<p class="pull-left question2"> {{$question}}</p>
<div class="form-group answer">
{{Form::label('', '')}}
{{Form::text('answer', '', ['class' => 'form-control', 'placeholder' => 'Type in your answer'])}}
</div>
</div>
</div>
#endforeach
<hr>
{{Form::submit('Save', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
And I am just using the resource in routes.
Your are calling a route templates/{id}/answers in your Blade view that is missing the {id} parameter. Reading the error thoroughly will help you understand.
Instead of writing:
Form::open(['action' => 'AnswersController#store', 'method' => 'POST'])
You write:
Form::open(['action' => ['AnswersController#store', $template_id], 'method' => 'POST'])
The $template_id will fill the {id} in your route URL templates/{id}/answers.
Still noob and learning Laravel, I am currently in the middle of a simple validation with FormRequest. What I am facing today is the edit of an existing entry.
I have written in my FormRequest that I want the name to be unique. It works perfectly but of course when I edit an existing entry, I cannot save it anymore, it already exists... of course it does since I am editing it.
I found the solution reading the documentation, but unfortunately, it does not work. Here's my code:
Routes:
Route::resource('editeurs', 'PublishersController');
Controller:
class PublishersController extends Controller
{
/* Update an existing publisher */
public function update($slug, PublisherRequest $request)
{
$publisher = Publisher::where('slug', $slug)->firstOrFail();
$input = $request->all();
$publisher->name = $input['name'];
$publisher->slug = my_slug($input['name']);
$publisher->save();
return redirect()->action('PublishersController#show', $publisher->slug);
}
}
FormRequest:
class PublisherRequest extends Request
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|unique:publishers,name,'.?????
];
}
}
If needed, the view:
#section('content')
<div class="row">
<h1 class="large-12 columns">Edition - {!! $publisher->name !!}</h1>
{!! Form::model($publisher, ['method' => 'PATCH', 'action' => ['PublishersController#update', $publisher->slug]]) !!}
<div class="large-12 columns">
{!! Form::label('name', 'Nom de l\'éditeur') !!}
{!! Form::text('name', null, ['placeholder' => 'Nom de l\'éditeur']) !!}
</div>
<div class="large-12 columns">
{!! Form::submit('Ajouter un éditeur', ['class' => 'button expand']) !!}
</div>
{!! Form::close() !!}
</div>
#stop
What is wrong with my code?
Here is how I would do it:
class PublishersController extends Controller
{
/* Update an existing publisher */
public function update($slug, PublisherRequest $request)
{
$publisher = Publisher::where('slug', $slug)->firstOrFail();
$this->validate($request, ['name' =>'required|unique:publishers,name,'.$publisher->id]);
$publisher->name = $request->input('name');
$publisher->slug = my_slug($publisher->name);
$publisher->save();
return redirect()->action('PublishersController#show', $publisher->slug);
}
}
OK, I found the solution. I needed to pass the slug of my current publisher.
public function rules()
{
$publisher = Publisher::where('slug', $this->editeurs)->first();
return [
'name' => 'required|unique:publishers,name,'.$publisher->id
];
}
This works.