Element not getting updated - laravel

well.
I've been trying to update an element of a post on my project. Thing is that I've followed the same process I've made with another thing and now It's not working on this one... I really don't know why.
This is inside the controller:
public function approve($id){
$id = Vulnerability::where('id', $id)->first();
$status = $id->status;
$data['verified'] = "Approved";
$id->update($data);
return redirect::back();
}
the status thing is not getting updated... what should i do? I'm sure the code is right because i used the same piece for another feature... but... now it's not working...
this is the form:
<form method="POST" action="/bounty/accept/{{ $id->id }}">
<input type="hidden" name="_method" value="patch">
{{ csrf_field() }}
<div class="col-lg-12 col-md-6 col-sm-12 col-xs-12">
<button class="btn btn-primary btn-lg full-width" type="submit" id="markSolved">Approve (please talk with the user by starting a thread bellow)</button>
</div>
</form>
this is the route:
Route::patch('/bounty/accept/{id}', [
'uses' => 'BountyController#approve',
])->middleware('auth');
It's correct... as far as i know...

Related

Laravel get route view without redirect

I am making a search in website.
public function search(Request $request)
{
$search_value = $request->search_txt;
$data_res = Data::Where('text', 'like', '%' . $search_value . '%')->get();
$navbar_search = Navbar::where('id','183')->first();
return redirect(route('response', $navbar_search->slug))->with('data_res',$data_res);
}
This is my controller function. I'm getting problem that i want to display data in the same page. I need to return view to this exact 'response' route and send slug. This redirect does not work, because $data_res after redirect is empty..
Routes:
Route::post('/search/search_res', 'SearchController#search')->name('search.srch');
Route::get('/{slug}', 'FrontEndPagesController#index')->name('response');
HTML:
<form class="form-horizontal" method="POST" action="{{ route('search.srch') }}">
{{ csrf_field() }}
<div class="main search_field">
<div class="input-group">
<input type="search" name="search_txt" class="form-control" value="{{ old('search_txt') }}" placeholder=" tekstas apie paieska ?" required maxlength="200" style="padding-left: 10px !important;">
<div class="input-group-append">
<button class="btn btn-secondary" type="submit">
<i class="fa fa-search"></i>
</button>
</div>
</div>
</div>
</form>
#if(!empty($data_res))
#foreach($data_res as $data)
{{ $data->id }}
#endforeach
#endif
With my little experience, I think when you redirect to another route and includes 'with', it stores the data in session.
you may want to access in the function FrontEndPagesController#index by
$data_res = session()->get('data_res');
then, to make it available for blade file, put it in return response like
return view('your response view', compact('data_res')

Laravel search functionality

I've got a searchbar on my homepage which looks like this:
<form action="{{ route('search', $query) }}" method="GET" role="search">
<div class="input-group mb-4 search_bar">
<input type="search" name="search" placeholder="Search..." aria-describedby="button-addon5" class="form-control search_input">
<div class="input-group-append">
<button id="button-addon5" type="submit" class="btn btn-primary"><i class="fa fa-search"></i></button>
</div>
</div>
</form>
My route looks like this:
Route::get('all-{query}-posts', 'SearchController#index')->where('query', '[A-Za-z0-9-]+')->name('search');
So basically I want the input of the searchbar in my url like this: /all-stuff-posts instead of the usual: ?search=stuff
It seems to automatically add the ?search=stuff to the end even though I didn't add that anywhere so that's the first problem.
The second problem is that I can only retrieve the query in the controller but that gives me an error in web.php because the query is still not set. Is there a different way of doing this that does work?
Change your form action method below like this
<form action="{{url('')}}/all-{{$query}}-posts" ...>
Used Post method.
<form action="{{ route('search', $query) }}" method="POST" role="search">
If you want to develop a search engine in your app, I will suggest the following. (One of the simplest ways).
Learn about POST, GET, PUT first.\
Then, My model like this
public function scopeSearchByKeyword($query, $keyword,$location)
{
if ($keyword!='' and $location!='') {
$query->where(function ($query) use ($keyword,$location) {
$query->where("title", "LIKE","%$keyword%")
->where("location_id", "$location")
->where("status", "1");
});
}
else
{
$query->where(function ($query) use ($keyword) {
$query->where("title", "LIKE","%$keyword%")
->where("status", "1");
});
}
return $query;
}
Here I am searching by title and location. It can output even if only a keyword is entered.
Then my controller like this:
public function search_kasblar(Request $request)
{
$inputs = $request->all();
$keyword = $inputs['search_keyword'];
$location = $inputs['location'];
$jobs= JobBoards::SearchByKeyword($keyword,$location)->get();
$total_res=count($jobs);
return view('jobs.search',compact('jobs','total_res','keyword'));
}
Here we can search for incoming data in the input.
So my view blade like this:
<div class="finderform">
{!! Form::open(array('url' => 'listings/search','class'=>'','id'=>'search','role'=>'form')) !!}
<div class="col-md-5 col-sm-5 no-padding"> <i class="fa fa-search local-search-ic"></i>
<input type="text" class="form-control" name="search_keyword" id="input-search-term" title="Search for..." placeholder="Search anything here" value="" autocomplete="off">
</div>
<div class="form-group col-md-5 col-sm-5 no-padding"> <i class="fa fa-map-marker local-search-ic ic-map-location"></i>
<div class="">
<select id="location" name="location" class="form-control">
<option value="">Select Location</option>
#foreach(\App\Location::orderBy('location_name')->get() as $location)
<option value="{{$location->id}}">{{$location->location_name}}</option>
#endforeach
</select>
</div>
</div>
<button type="submit" class="btn tp-btn-default tp-btn-lg">Search</button>
{!! Form::close() !!}
You can use like this.
And use POST in your router...

PUT/POST in Laravel

I'm brand new to Laravel and am working my way through the [Laravel 6 from Scratch][1] course over at Laracasts. The course is free but I can't afford a Laracasts membership so I can't ask questions there.
I've finished Section 6 of the course, Controller Techniques, and am having unexpected problems trying to extend the work we've done so far to add a few new features. The course has students build pages that let a user show a list of articles, look at an individual article, create and save a new article, and update and save an existing article. The course work envisioned a very simple article containing just an ID (auto-incremented in the database and not visible to the web user), a title, an excerpt and a body and I got all of the features working for that, including updating an existing article and saving it.
The update form sets method to POST but then uses a #METHOD('PUT') directive to tell the browser that it is actually supposed to do a PUT. This worked perfectly in the original code. However, now that I've added two more fields to the form, when I click Submit after editing an existing record, the save fails with this message:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The PUT method is not supported for this route. Supported methods: GET, HEAD, POST.
http://localhost:8000/articles
I don't understand why adding two fields to the form would cause this to break. Can someone enlighten me? I added the two new fields/columns to the migration and ran migrate:rollback and migrate. I've also added the new fields/columns to the fillable attribute and added validations for them in the ArticlesController.
Here is my routing:
Route::get('/articles', 'ArticlesController#index');
Route::post('/articles', 'ArticlesController#store');
Route::get('/articles/create', 'ArticlesController#create');
Route::get('/articles/{article}', 'ArticlesController#show');
Route::get('/articles/{article}/edit', 'ArticlesController#edit');
Route::put('/articles/{article}', 'ArticlesController#update');
//Route::delete('/articles/{article}', ArticlesController#destroy');
This is my ArticlesController:
<?php
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function index()
{
$articles = Article::latest()->get();
return view ('articles.index', ['articles' => $articles]);
}
public function show(Article $article)
{
return view('articles.show', ['article' => $article]);
}
public function create()
{
return view('articles.create');
}
public function store()
{
//Stores a NEW article
Article::create($this->validateArticle());
return redirect('/articles');
}
public function edit(Article $article)
{
return view('articles.edit', ['article' => $article]);
}
public function update(Article $article)
{
//Updates an EXISTING article
$article->update($this->validateArticle());
return redirect('/articles/', $article->id);
}
public function validateArticle()
{
return request()->validate([
'title' => ['required', 'min:5', 'max:20'],
'author' => ['required', 'min:5', 'max:30'],
'photopath' => ['required', 'min:10', 'max:100'],
'excerpt' => ['required', 'min:10', 'max:50'],
'body' => ['required', 'min:50', 'max:500']
]);
}
public function destroy(Article $article)
{
//Display existing record with "Are you sure you want to delete this? Delete|Cancel" option
//If user chooses Delete, delete the record
//If user chooses Cancel, return to the list of articles
}
}
Here's my edit form, edit.blade.php:
#extends('layout')
#section('content')
<div id="wrapper">
<div id="page" class="container">
<h1>Update Article</h1>
<form method="POST" action="/articles">
#csrf
#method('PUT')
<div class="form-group">
<label class="label" for="title">Title</label>
<div class="control">
<input class="form-control #error('title') errorborder #enderror" type="text" name="title" id="title" value="{{ $article->title }}">
#error('title')
<p class="errortext">{{ $errors->first('title') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="author">Author</label>
<div class="control">
<input class="form-control #error('author') errorborder #enderror" type="text" name="author" id="author" value="{{ $article->author }}">
#error('title')
<p class="errortext">{{ $errors->first('author') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="photopath">Path to Photo</label>
<div class="control">
<input class="form-control #error('photopath') errorborder #enderror" type="text" name="photopath" id="photopath" value="{{ $article->photopath }}">
#error('title')
<p class="errortext">{{ $errors->first('photopath') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="excerpt">Excerpt</label>
<div class="control">
<textarea class="form-control #error('excerpt') errorborder #enderror" name="excerpt" id="excerpt">{{ $article->excerpt }}</textarea>
#error('excerpt')
<p class="errortext">{{ $errors->first('excerpt') }}</p>
#enderror
</div>
</div>
<div class="form-group">
<label class="label" for="body">Body</label>
<div class="control">
<textarea class="form-control #error('body') errorborder #enderror" name="body" id="body">{{ $article->body }}</textarea>
#error('body')
<p class="errortext">{{ $errors->first('body') }}</p>
#enderror
</div>
</div>
<div class="control">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
</div>
</div>
#endsection
Is there anything else you need to see?
[1]: https://laracasts.com/series/laravel-6-from-scratch/episodes/33?autoplay=true
Your Laravel route is:
Route::put('/articles/{article}', 'ArticlesController#update');
So your form action url should match that uri:
<form action="{{ url('/articles/'.$article->id) }}">
where the {article} parameter is the record id (you can read more about in the docs here).
Then in your controller update() method, you have:
return redirect('/articles/', $article->id);
which means redirect to /articles with status code $article->id (you can read more about in the docs here). I think you are trying to redirect to the show route, which is:
Route::get('/articles/{article}', 'ArticlesController#show');
So change the , (comma) to a . (dot) to concatenate the article id with the uri:
return redirect('/articles/' . $article->id);
The route in the form for /articles, However your route for updating should be /articles/{article}
Try this:
<form method="POST" action="/articles/{{ $article->id }}">

Laravel 5.7 using same url action for insert and update with #yield in blade template

I am using laravel 5.7 and I am using one form for inserting and updating. In form action I want to use #yield() for laravel route to get the id for updation. Every thing is fine but I can't use #yield() method. Here is my code, problem is only in action of the form.
<form class="form-horizontal" action="{{ url('/todo/#yield('editId')') }}" method="post">
{{csrf_field()}}
#section('editMethod')
#show
<fieldset>
<div class="form-group">
<div class="col-lg-10">
<input type="text" name="title" placeholder="Title" value="#yield('editTitle')" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" placeholder="Body" name="body" rows="5" id="textarea">#yield('editBody')</textarea>
<br>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
I have also checked with single and double quotes.
action="/todo/#yield('editid')"
When I use simple this method then after submitting it redirects me to localhost and with an error page not found. In laravel 5.4 it works. but not in laravel 5.7. Any help would be appreciated Thanks
Here is my edit.blade.php from where I am using the #section and #yield
#extends('Todo.create')
#section('editId',$item->id)
#section('editTitle',$item->title)
#section('editBody',$item->body)
#section('editMethod')
{{ method_field("PUT") }}
#endsection
Controller store edit and update methods are
public function store(Request $request)
{
$todo = new todo;
$this->validate($request,[
'body'=>'required',
'title'=>'required|unique:todos',
]);
$todo->body = $request->body;
$todo->title = $request->title;
$todo->save();
return redirect("todo");
}
public function edit($id)
{
$item = todo::find($id);
return view("Todo.edit",compact('item'));
}
public function update(Request $request, $id)
{
$todo = todo::find($id);
$this->validate($request,[
'body'=>'required',
'title'=>'required',
]);
$todo->body = $request->body;
$todo->title = $request->title;
$todo->save();
return redirect("/todo");
}
To answer the OP actual question you would need to do
#section('editId', "/$item->id") or #section('editId', '/'.$item->id')
{{ url('/todo') }}#yeild('editId')
But much better to do
{{ url('/todo/'.(isset($item) ? $item->id : '')) }}
Or for PHP >= 7
{{ url('/todo/'.($item->id ?? '')) }}
As apokryfos already mentioned - #yield is thought to make reusing your templates easier.
If you simply want to determine (for example) which action should be called afterwards you should better do something like that:
#extends('Todo.create')
<form class="form-horizontal" action="/todo/{{ isset($item) ? $item->id : '' }}" method="post">
#if( ! isset($item))
{{ method_field("PUT") }}
#else
{{ method_field("PATCH") }}
{{csrf_field()}}
<fieldset>
<div class="form-group">
<div class="col-lg-10">
<input type="text" name="title" placeholder="Title" value="{{ isset($item) ? $item->title : '' }}" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" placeholder="Body" name="body" rows="5" id="textarea">{{ isset($item) ? $item->body : '' }}</textarea>
<br>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
Also as I remember the method field should always come first to make sure it's recognized correctly. Additionally you shouldn't need url() to generate the url I think.
No need for a second blade. Simply inject the variables directly into the template and make sure they are set before you access them. I didn't try it but I'd think that it should work.

not getting checkbox element value from form

I have a small form in Laravel 5.4 which has a checkbox and a text box. The issue is that when I post the form, the checkbox value is not coming through the request. I have custom styling on the checkbox but surely it can't be that?
I've been looking at this for a while, and everything looks normal. My code is below:
<form method="post" action="{{ route('admin.settings.save') }}">
{{ csrf_field() }}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label><b>Site Name</b></label>
<p>This is the name of your LaravelFileManager instance.</p>
<input name="siteName" id="siteName" class="form-control" value="{{ \App\Helpers\ConfigHelper::getValue('site_name') }}" />
</div>
<div class="form-group">
<label><b>Footer Message</b></label>
<p>You can customise the footer message for the application.</p>
<div class="checkbox">
<label>
<input type="checkbox" name="showFooter" id="showFooter" checked="{{ \App\Helpers\ConfigHelper::getValue('show_footer_message') }}"> Show footer message
</label>
</div>
</div>
<button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Save Changes</button>
</div>
</div>
</form>
My controller code is as such:
public function saveSettings(Request $request) {
$siteName = $request->input('siteName');
$showFooter = $request->input('showFooter');
ConfigHelper::setValue('site_name', $siteName);
ConfigHelper::setValue('show_footer_message', $showFooter);
return redirect()->route('admin.settings')->with('result', 'Settings saved.');
}
My route:
Route::post('settings/save', ['uses' => 'Admin\SettingsController#saveSettings'])->name('admin.settings.save');
I've also done a vardump on the $request variable and even that is missing the check box value:
array(2) {
["_token"]=> string(40) "sgyO7Kkz1ljsYEZ1G5nkj4uVbmFZqiTMbpK9P6Bi"
["siteName"]=> string(16) "File Manager 1.0"
}
It's missing the 'showFooter' variable.
Not quite sure where to go with this one. Any help appreciated.
So I got this working in the end. Using help from the comments:
public function saveSettings(Request $request) {
$siteName = $request->input('siteName');
$showFooter = $request->has('showFooter');
ConfigHelper::setValue('site_name', $siteName);
ConfigHelper::setValue('show_footer_message', $showFooter);
return redirect()->route('admin.settings')->with('result', 'Settings saved.');
}
For some reason, using $request->input('showFooter') wasn't working properly. $request->get('showFooter') brings a result when true, so adding the ternary makes it work every time.

Resources