Laravel problems with redirect - laravel

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);
}
}

Related

Laravel 8 form select option dropdown problem

Am having problem here
I have two tables
Department table
with fields
id dept_code dept_name
I also have Persons table
with fields
id Persons_names Dept_name Position_held
I have a data entry form to enter data to the Persons_table
the problem am having is I want to create select option to get Dept_name From Department_table but am always getting undefined value error.
this is my form
{!! Form::open(['url' => 'persons_form/store']) !!}
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-6">
{{Form::label('FullNames', 'Fullnames')}}
{{Form::text('names', '',['class'=>'form-control','placeholder'=>'Persons Fullnames'])}}
</div>
<div class="form-group col-md-6">
{{Form::label('Department', 'Department')}}
#foreach ($depts as $dept)
{{
Form::select('department', $dept->department_name, null, ['class'=>'form-control','placeholder' => 'Select Department'])
}}
#endforeach
</div>
<div class="form-group col-md-12">
{{Form::label('Position', 'Position')}}
{{Form::text('level', '',['class'=>'form-control','placeholder'=>'Departmental Position'])}}
</div>
</div>
<div>
{{Form::submit('Save Data',['class'=>'btn btn-outline-primary text-center',])}}
</div>
{!! Form::close() !!}
this is my personsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\People;
class PeopleController extends Controller
{
public function index()
{
$depts = DB::table('departments')->select('department_name')->get();
return view('strategic_plan.people_form', ['depts' => $depts]);
}
public function create()
{
$depts = DB::table('departments')->pluck('department_name');
}
public function store(Request $request)
{
$this->validate($request,[
'names'=>'required',
'department'=>'required',
'level' =>'required'
]);
$persons =new People;
$persons->names=$request->input('names');
$persons->department=$request->input('persons');
$persons->level=$request->input('level');
$dept->save();
return redirect('/people')->with('message','Person Added Succesifully');
}
public function show()
{
$persons = People::all()->sortByDesc("id");
return view('strategic_plan.people',compact('persons'));
}
public function edit($id)
{
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
When I try to open the Form am getting
$depts is undefined
Try using compact, And get #dd in your blade of $depts and share the code.
Use
return view('strategic_plan.people_form', ['depts' => $depts]);
instead of
return view('strategic_plan.people_form', compact('depts');
write it down

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() !!}

How to update user status using button without update all parameters in laravel

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 :)

Issues with search query

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.

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