Issues with search query - laravel

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.

Related

Updating email/password not working, undefined variable

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.

Laravel problems with redirect

So I am working on a laravel project and I want that if a user types in their order code, the order will show up with the details. For some reason, the order code doesn't get through the if statement, because I get the output 'Order not found.' all the time, even if I type in an order code that is present in my orders table.
TrackController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Order;
class TrackController extends Controller
{
public function index()
{
return view ('track.index');
}
public function show($id)
{
$order = Order::where('code', $id)->first();
return view('track.show',[
'order' => $order
]);
}
public function redirect(Request $request)
{
$orderCode = $request->input('order-track-id');
$order = Order::where('code', $orderCode)->first();
if(!$order){
return redirect('/track')->with('error', 'Order not found.');
}else{
return redirect('/track/' . $order->code);
}
}
}
web.php
Route::get('/track', 'TrackController#index');
Route::post('/track/redirect', 'TrackController#redirect');
Route::get('/track/{id}', 'TrackController#show');
track.index
#extends('layouts/app')
#section('content')
<div class="container">
<div class="row justify-content center">
{!! Form::open(['action' => 'TrackController#redirect', 'method' => 'post']) !!}
{!! csrf_field() !!}
<input type="number" name="input-order-track-id" id="order-track-id">
{{ Form::button('Track', ['type' => 'submit', 'class' => 'btn btn-primary'] ) }}
{!! Form::close() !!}
</div>
</div>
#endsection
What am I doing wrong and why isn't my function putting me through to the show function in the TrackController?
In your redirect controller function.
public function redirect(Request $request)
{
$orderCode = $request->input('input-order-track-id');
$orders = Order::where('code', $orderCode)->get();
if($orders->isEmpty()){
return redirect('/track')->with('error', 'Order not found.');
}else{
$order = Order::where('code', $orderCode)->first();
return redirect('/track/' . $order->code);
}
}

How to fix"Illuminate\Support\Collection::get(), 0passed in /AMPPS/www/lsapp/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php"

In an attempt to program a search bar, I created a GET method and added a new controller where it gets the relevant data and returns it with the view.
//This is the form in the view named "index.blade.php"
{!! Form::open(['action' => 'SearchesController#search', 'method' => 'GET']) !!}
<form class="form-inline md-form mr-auto mb-4">
{{Form::text('search', '', ['class'=>'form-control', 'placeholder'=>'Search Anything'])}}
<button class="btn aqua-gradient btn-rounded btn-sm my-0" type="submit">Search</button>
</form>
{!! Form::close() !!}
//---------------------------------------------------------
//This is in the "web.php"
Route::get('/posts/search', 'SearchesController#search');
//---------------------------------------------------------
//The following code is the controller named "SearchesController.php"
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Post;
use DB;
use Illuminate\Support\Facades\Auth;
class SearchesController extends Controller
{
public function search(Request $request)
{
$this->validate($request, [
'search' => 'required',
]);
$search = metaphone($request->input('search'));
$posts = Post::where('sounds_like','LIKE',"%{$search}%")
->orderBy('title', 'desc')
->paginate(10)
->get();
return view('posts.index')->with('posts',$posts);
}
}
I expected the output of a view with all the data returned with the view, but instead got the error message :
"Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in /Applications/AMPPS/www/lsapp/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php on line 23 and at least 1 expected"
You desn't need a get() if you are using paginate(). Paginate will execute the query too and will create a collection, and the get() method will be executed as an instance of this get() and will require the key parameter . So you can remove it:
public function search(Request $request)
{
// ...
$posts = Post::where('sounds_like','LIKE','%'. $search . '%')
->orderBy('title', 'desc')
->paginate(10);
return view('posts.index')->with('posts',$posts);
}
Not related to the error, but also you have a form inside a form. Choose one and remove the other:
{!! Form::open(['action' => 'SearchesController#search', 'method' => 'GET', 'class'=>'form-inline md-form mr-auto mb-4']) !!}
{{Form::text('search', '', ['class'=>'form-control', 'placeholder'=>'Search Anything'])}}
<button class="btn aqua-gradient btn-rounded btn-sm my-0" type="submit">Search</button>
{!! Form::close() !!}

Laravel error "Missing required parameters for Route" when I use a form with a foreach loop

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.

Allow saving an existing entry in Laravel with FormRequest and unique

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.

Resources