Laravel 5.2 add params to url - php

I need to pass a value from a form(dropdwon) and append this value to a url.
My Routes are:
Route::get('menues/{city?}', 'PagesController#menue');
Route::post('/', 'PagesController#menue');
I have a simple form:
{!!Form::open(array('action' => 'PagesController#menue', 'method' => 'POST'))!!}
{!! Form::select('city', array('heilbronn' => 'Heilbronn', 'stuttgart' => 'Stuttgart')) !!}
{!!Form::submit('Senden')!!}
{!!Form::close()!!}
And this Controller:
public function menue(Request $request, $city = null) {
$searchinput = $request->input('city');
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}]);
if(!is_null($city) && !is_null(User::where('city', $city)->first())) {
$restaurants->where('city', '=', $city);
}
$restaurants = $restaurants->get();
return view('pages.menues')->withRestaurants($restaurants)
//->withArticles($articles)
->withCity($city)
->withSearchinput($searchinput);
}
I need to append the value ($searchinput) from the previous page to show only entries for a particular city.

You need to change your form method attribute to GET, then in your controller you can do follow:
public function menue(Request $request) {
$city = $request->city;
// bla-bla-bla
if ( ! is_null($city) && && ! is_null(User::where('city', $city)->first()) {
// bla-bla
}
// return
}

Related

How can I fix Laravel comments policy not working?

I am using inertia JS.
I created a forum where you can manage your posts and comments (CRUD).
Normally, the one who can modify or delete his post or comment is the one who created it and the administrator.
I was able to set up a policy for the post but for the comment it does not work. I need your help to fix this.
This is my show function for post and comments
public function show(Post $post, Comment $comment)
{
usleep(500000);
$post->incrementReadCount();
$updateableCommentIds = $post->comments
->map(function ($comment) {
if (Auth::user()->can('update', $comment)) {
return $comment->id;
}
})
->filter();
return Inertia::render('Frontend/Forum/Helpers/PostDetails', [
'post' => PostResource::make(
$post->load('user')->loadCount('comments')
),
'comments' => CommentResource::collection(
Comment::where('post_id', $post->id)
->with('user')
->paginate(10)
->withQueryString()
),
'categories' => Category::all(),
'can' => [
'edit' => Auth::check() && Auth::user()->can('edit', $post),
'commentEdit' => $updateableCommentIds
]
]);
}
This's my comment policy
class CommentPolicy
{
use HandlesAuthorization;
public function update(User $user, Comment $comment): bool
{
return $user->is_admin || $user->id === (int) $comment->user_id;
}
}
This's my vue file
<div
v-if="can.commentEdit.includes(comment.id)"
>
//show me this if im the auther of this comment
</div>
I already tried but it doesn't work either
public function show(Post $post)
{
$canUpdateComments = $post->comments->every(function ($comment) {
return Auth::user()->can('update', $comment);
});
// Return the view with the ability to update the comments
return view('posts.show', compact('post', 'canUpdateComments'));
}
I just noticed that I had a commentResource and just with that I found the solution instead of checking each time on the post not directly on the comment...
class CommentResource extends JsonResource
{
public function toArray($request)
{
return [
...
'can' => [
'edit' => Auth::user()->can('update', $this->resource)
]
];
}
}

How to bypass multiple parameter from url to controller

I have 2 parameters that I put in my url. What I want is how to get these 2 parameters, so it can be read from my controller.
I've try this so the controller can read the parameter:
$id = Input::get('id');
but when I check with dd, the parameter is null
Here is my code:
The link a href on view:
{{ URL('/lap_spd/tambahspd/'.$items->nosurat.'/'.$items->id )}}
web php :
Route::get('lap_spd/tambahspd/{id}/{nosurat}', function($id, $nosurat){
return redirect()->action(
'lapspdController#tambahuwong', ['id' => $id], ['nosurat' => $nosurat]);
});
lapspdController php:
public function tambahuwong($id, $nosurat) {
$id = Input::get('id');
$nosurat = Input::get('nosurat');
$data3 = DB::table('list_nama')
->where('id_nosurat', 'nosurat')
->toSql();
dd($data3);
so the output that I want - is the parameter can pass to variable on controller.
Thanks for respone before and sorry for my bad english.
Pass the parameters in a single array in your web.php file
return redirect()->action(
'lapspdController#tambahuwong', ['id' => $id, 'nosurat' => $nosurat]);
In lapspdController php:
public function tambahuwong($id, $nosurat) {
//remove these lines and use the variables from the parameters directly
//$id = Input::get('id');
//$nosurat = Input::get('nosurat');
$data3 = DB::table('list_nama')
->where('id_nosurat',$nosurat)
->toSql();
dd($data3);
in view:
in route:
Route::get('lap_spd/tambahspd/{id}/{nosurat}','HomeController#tambahuwong')
->name('check');
in controller:
public function tambahuwong($id,$nosurat) {
$check_id=$id;
$nosurat_name=$nosurat;
dd($check_id);
dd($nosurat_name);
}
Does it work if you change
return redirect()->action(
'lapspdController#tambahuwong', ['id' => $id], ['nosurat' => $nosurat]);
});
to
return redirect()->action(
'lapspdController#tambahuwong', ['id' => $id, 'nosurat' => $nosurat]);
});
?

Laravel update makes new table rule instead of updating

I have a company table and an attributes table with all sorts of value in it.
One company hasMany attributes and an attribute belongsTo a company.
Now I have a value inside the attributes table with a 'account_nr_start' (for example, when a new user is added to a company its account_id starts counting up from 1000).
Controller:
public function __construct(Company $company, User $user)
{
if(Auth::user()->usertype_id == 7)
{
$this->company = $company;
}
else
{
$this->company_id = Auth::user()->company_id;
$this->company = $company->Where(function($query)
{
$query->where('id', '=', $this->company_id )
->orWhere('parent_id','=', $this->company_id);
}) ;
}
$this->user = $user;
$this->middleware('auth');
}
public function edit(Company $company, CompaniesController $companies)
{
$companies = $companies->getCompaniesName(Auth::user()->company_id);
$attributes = $company->attributes('company')
->where('attribute', '=', 'account_nr_start')
->get();
foreach ($attributes as $k => $v) {
$nr_start[] = $v->value;
}
return view('company.edit', ['company' => $company, 'id' => 'edit', 'companies' => $companies, 'nr_start' => $nr_start]);
}
public function update(UpdateCompanyRequest $request, $company, Attribute $attributes)
{
$company->fill($request->input())->save();
$attributes->fill($request->only('company_id', 'attribute_nr', 'value'))->save();
return redirect('company');
}
HTML/Blade:
<div class="form-group {{ $errors->has('_nr_') ? 'has-error' : '' }}">
{!! HTML::decode (Form::label('account_nr_start', trans('common.account_nr_start').'<span class="asterisk"> *</span>', ['class' => 'form-label col-sm-3 control-label text-capitalize'])) !!}
<div class="col-sm-6">
{!! Form::text('value', $nr_start[0], ["class"=>"form-control text-uppercase"]) !!}
{!! $errors->first('account_nr_start', '<span class="help-block">:message</span>') !!}
</div>
</div>
When I update a company now, it will upload like the last input here: :
So it makes a new rule, while it needs to edit the current attribute rule instead of making a new rule with an empty company_id/attribute.
If I understand what you are trying to do, I think this will fix your problem. The issue you have is the Attribute model is a new instance of the model rather than retrieving the model you need.
before running fill() from the attributes method try this
$new_attribute = $attributes->where('company_id', '=', $company->id)->where('attribute', '=', 'account_nr_start')->first();
Then run the fill()
$new_attribute->fill($request->only('company_id', 'attribute_nr', 'value'))->save();

Laravel error when hasOne has nothing

I am trying to pre-populate some fields in a form and I'm new to relationships.
My controller:
public function index($supplierId) {
$Supplier = new Supplier;
$supplierData = Supplier::find($supplierId);
$supplierData->countryId = ($supplierData->countryId == 0 ? 258 : $supplierData->countryId);
$supplierData->writtenLanguageId = ($supplierData->writtenLanguageId == 0 ? 1 : $supplierData->writtenLanguageId);
$supplierData->paymentTermsId = ($supplierData->paymentTermsId == 0 ? 5 : $supplierData->paymentTermsId);
$countries = Countries::lists('country', 'id');
$languages = Languages::lists('language', 'id');
$paymentTerms = PaymentTerms::lists('term', 'id');
$leadTimes = Leadtimes::lists('leadtime', 'id');
return View::make('supplier.supplier', array(
'supplierData' => $supplierData,
'countries' => $countries,
'languages' => $languages,
'paymentsTerms' => $paymentTerms,
'leadtimes' => $leadTimes
));
}
My model:
class Supplier extends Eloquent {
protected $table = 'suppliers';
public function email() {
return $this->hasOne('SupplierEmail', 'supplierId');
}
public function creditLimits() {
return $this->hasOne('SupplierCreditLimits', 'supplierId');
}
public function website() {
return $this->hasOne('SupplierWebsite', 'supplierId');
}
}
The problem:
<div class='col-xs-12 col-md-6'>{{Form::text('website', $supplierData->website->website, array('class' => 'form-control input-sm'))}}</div>
When there is no row (there is no record), I get:
Trying to get property of non-object (View: C:\wamp\vhosts\view\laravel\app\views\supplier\supplier.blade.php)
How do I get this to work properly?
In your view, use isset to check the value first:
<div class='col-xs-12 col-md-6'>
{{Form::text('website',
isset($supplierData->website->website) ? $supplierData->website->website : '',
array('class' => 'form-control input-sm'))
}}
</div>
Or, better yet, handle this logic in your controller and pass the result to the view:
$supplierData->URL = isset($supplierData->website->website) ? $supplierData->website->website : '';

Laravel search query with multiple conditions

Newbie to PHP/Laravel here so please be patient.
I have a webpage that is searching based on 3 criteria for dogs , breed, sex and radius.
here is the relevant code:
search page
<div class="col-md-12 zero-pad-left zero-pad-right">
{{ Form::open(array('action' => array('DogsController#index'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
<div id="prefetch">
{{ Form::text('search-breed', null, array('class' => 'typeahead form-group form-control', 'placeholder' => 'Search by breed here...')) }}
{{ Form::text('sex', null, array('class' => 'form-group form-control', 'placeholder' => 'Search by sex here...')) }}
{{ Form::text('miles', null, array('class' => 'form-group form-control', 'placeholder' => 'Search by distance here...')) }}
</div>
{{ Form::submit('Search', array('class' => 'btn btn-default search-bar-btn')) }}
{{ Form::close() }}
ControllerPage
class DogsController extends \BaseController {
public function __construct()
{
// call base controller constructor
parent::__construct();
// run auth filter before all methods on this controller except index and show
$this->beforeFilter('auth', array('except' => array('show')));
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
if (Input::has('search')) {
$queryString = Input::get('search');
$dogs = Dog::where('name', 'LIKE', "%$queryString%")->orderBy('name')->paginate(5);
}
elseif (Input::has('search-breed'))
{
$dogs = Dog::whereHas('breed', function($q)
{
$queryString = Input::get('search-breed');
$q->where('name', 'LIKE', "%$queryString%");
})->orderBy('name')->paginate(5);
} //end elseif
else {
$dogs = Dog::orderBy('name')->paginate(5);
} //end else
return View::make('dogs.index')->with(array('dogs' => $dogs));
} //end function index()
when i enter a search for poodle, male, within 20 miles, the url shows as follows:
http://ruff-love.dev/dogs?search-breed=poodle&sex=M&miles=20
The search currently works ok when searching for just breed.
I cant seem to figure out the syntax to add the SEX and RADIUS criteria also.
it should allow for those criteria to be null and still perform the query.
any advice would be greatly apprecaited
You can use query scopes http://laravel.com/docs/eloquent#query-scopes to make it verbose and easier in your controller (or wherever you will be doing it in future) then chain them according to your needs:
// Dog model
public function scopeSearchBreed($query, $breed)
{
$query->whereHas('breed', function ($q) use ($breed) {
$q->where('name', 'like', "%{$breed}%");
});
}
public function scopeWithinRadius($query, $radius)
{
$query->where(...); // do math here
}
Then all you need is this:
public function index()
{
$q = Dog::query();
if (Input::has('search'))
{
// simple where here or another scope, whatever you like
$q->where('name','like',Input::get('search'));
}
if (Input::has('search-breed'))
{
$q->searchBreed(Input::get('search-breed'));
}
if (Input::has('sex'))
{
$q->where('sex', Input::get('sex'));
}
if (Input::has('radius'))
{
$q->withinRadius(Input::get('radius'));
}
$dogs = $q->orderBy(..)->paginate(5);
// ...
Here's one possible solution, I think there are probably others. Create an empty query builder with the query() function and add the non-null clauses to it, then call the paginate() function at the end.
$builder = Dogs::query();
if (Input::has('search')) {
$queryString = Input::get('search');
$builder->where('name', 'LIKE', "%$queryString%");
}
// ... more clauses from the querystring
$dogs = $builder->orderBy('name')->paginate(5);
$builder = Dogs::query();
$term = Request::all();
if(!empty($term['breed'])){
$builder->where('breed','=',$term['breed']);
}
if(!empty($term['sex'])){
$builder->where('sex','=',$term['sex']);
}
if(!empty($term['radius'])){
$builder->where('radius','=',$term['radius']);
}
$result = $builder->orderBy('id')->get();
$area = Area::query();
if (Input::has('search')) {
$queryString = Input::get('search');
$area->where('name', 'LIKE', "%" . $queryString . "%");
}
$result = $area->orderBy('name')->paginate(5);

Categories