Laravel Cannot retrieve a specific record from a form - laravel

I am outputting a list from a database table 'books' like this:
function edit()
{
$books = Book::all();
return view('layouts/editbooks', ['books' => $books]);
}
And displaying them like this:
#extends('layouts.master')
#section('title')
#section('content')
<h1>Edit Book</h1>
<form action="{{url('editbook')}}" method="GET">
{{ csrf_field() }}
#foreach ($books as $book)
<div>
<label>{{$book->title}}</label>
<input type='radio' value='{{$book->id}}' name='books[]'/>
</div>
#endforeach
<input type="submit" class="btn btn-warning form-control" value="Edit">
</form>
#endsection
I then want user to choose which record they want to edit by selecting a radio button, and upon clicking a submit button, redirect user to a new page with details of a book.
Therefore I am trying to get a book id from radio button and then if id matches, display everything from that record:
function editing(Request $request)
{
$edit = $request->books;
return view('layouts/editing', ['edit' => $edit]);
}
function updateEdit()
{
$books = DB::table('books')->where('id', $edit)->first();
}
And that is displayed in a view:
#extends('layouts.master')
#section('title')
#section('content')
<h1>Delete Book</h1>
<form action="{{url('removebook')}}" method="POST">
{{ csrf_field() }}
<div>
<input name="name" type="textbox" value="{{ old('name', $edit['name']) }}"/>
</div>
<input type="submit" name="submitBtn" value="Delete Book">
</form>
#endsection
However I get an error message saying:
Undefined index: name (View: C:\xampp\htdocs\laraveladvweb\resources\views\layouts\editing.blade.php)
What is causing the issue?

Isn't $edit just the id of the book?
try this
function editing(Request $request)
{
$edit = $request->books;
$book = DB::table('books')->where('id', $edit)->first();
return view('layouts/editing', ['edit' => $book]);
}
#extends('layouts.master')
#section('title')
#section('content')
<h1>Delete Book</h1>
<form action="{{url('removebook')}}" method="POST">
{{ csrf_field() }}
<div>
<input name="name" type="textbox" value="{{ old('name', $edit['name']) }}"/>
</div>
<input type="submit" name="submitBtn" value="Delete Book">
</form>
#endsection

Related

Laravel 9 Update Form Values with controller MVC

I want to update my input values ​​in the form in my database by sending them from the route to the controller. What am I doing wrong? Can you help me? I tried the #method('PUT') method before. It's a bit confusing. I am sharing the codes. I will be very happy if you can help, thank you.
...
<div class="modal-body">
<div class="form-group text-center"
style="position: center; margin-top:3em;">
<form action="{{ 'edit-name/' . $user->id }}" method="POST"
enctype="multipart/form-data">
#csrf
<label for="fname">
{{ __('welcome.fullname') }}:</label>
<input name="name1" type="hidden"
placeholder="{{ $user->name }}">
</div>
<br>
<br>
<br>
{{-- //Name Edit Button --}}
<button type="submit"
class="btn-sm app-btn-secondary">{{ __('welcome.confirm') }}</button>
...
my route and controller
...
Route::get('edit-name/{id}', [HomeController::class, 'editname']);
...
...
public function editname(Request $request, $id){
dd(1);
$user= Auth::user();
dd($user);
$id=$request->id;
$name=$request->input('name1');
$isUpdateSuccess = User::where('id', $id) ->update(['name1'=>$name, ]);
if($isUpdateSuccess)
echo '<h1>Update Success</h1>';
else echo '<h1>Update Failed </h1>';
}
...
you are sending the data from modal using POST method but in your route you are using this data by GET method. I will suggest you to use POST method so that user_id will not be append in URL, so try this,
Your blade
<div class="modal-body">
<div class="form-group text-center" style="position: center; margin-top:3em;">
<form action="{{ 'edit-name' }}" method="POST" enctype="multipart/form-data">
#csrf
<input type="hidden" name="id" placeholder="{{ $user->id }}">
<label for="fname">
{{ __('welcome.fullname') }}:</label>
<input name="name1" type="text" placeholder="{{ $user->name }}">
</div>
<br>
<br>
<br>
{{-- //Name Edit Button --}}
<button type="submit" class="btn-sm app-btn-secondary">{{__('welcome.confirm') }}</button>
Your route
Route::post('/edit-name', [HomeController::class, 'editname']);
Your controller
public function editname(Request $request){
// dd(1);
$user= Auth::user();
// dd($user);
$id=$request->id;
$name=$request->input('name1');
$isUpdateSuccess = User::where('id', $id) ->update(['name1'=>$name, ]);
if($isUpdateSuccess)
echo '<h1>Update Success</h1>';
else echo '<h1>Update Failed </h1>';
}
Change action
from
action="{{ 'edit-name/'. $user->id }}"
to
action="{{ url('edit-name',$user->id) }}"

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...

Edit function not working in CRUD form (Laravel)

I've created a CRUD form called 'Groups'. The Create and Delete functions work, but the 'Edit' throws up an error:
"Undefined variable: group (View:
C:\wamp64\www\sites\jointpromote2\resources\views\groups\edit.blade.php
The error points to this line of code:
<input type="text" class="form-control" name="group_name" value="<?php echo e($group->group_name); ?>" />
I've tried several things but nothing fixes the issue.
Here is my http/controllers/GroupController.php
{
$event = Group::find($id);
return view('groups.edit', compact('group'));
}
Here's my database/migrations/create_groups_table.php
public function down()
{
Schema::dropIfExists('groups');
}
And here's the edit.blade.php
#section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Update a Group</h1>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
<br />
#endif
<form method="post" action="{{ route('groups.update', '$group->id') }}">
#method('PATCH')
#csrf
<div class="form-group">
<label for="group_name">Group Name:</label>
<input type="text" class="form-control" name="group_name" value="{{ $group->group_name }}" />
</div>
<div class="form-group">
<label for="group_description">Group Description:</label>
<input type="text" class="form-control" name="group_description" value="{{ $group->group_description }}" />
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
#endsection
You are using "compact" method in wrong way.
https://www.php.net/manual/en/function.compact.php
try with this
{
$event = Group::find($id);
return view('groups.edit', compact($event));
}
You're passing wrong variable from your GroupController to your edit.blade.php view. Change your GroupController to this:
{
$group= Group::find($id);
return view('groups.edit', compact('group'));
}
All should be working now.
Your variable name is event but you are compacting group and using group variable in blade. Change the variable name in controller and everything will be fine.
public function edit($id) {
$group = Group::find($id);
return view('groups.edit', compact('group'));
}
You write action is in the wrong way. Try copy and paste below code
<form method="post" action="{{ route('groups.update',
$group->id) }}">
You have to remove '.' from $group->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.

Laravel 5 session()->keep method not working

I have a view with an input date field and a table beneath that. The table is populated based on the date entered. When the date is entered I use a POST method on the form which handles the DB request and returns the same view with the data. I'd like to also return the original date that was entered. I tried session()->keep and flashOnly methods. None return the input date to the view.
My controller:
public function groupTestAthletes(Request $request)
{
$inputDate = null;
$tests = null;
if ($request['tgroupdate']){
$inputDate = Carbon::createFromFormat('d/m/Y', $request['tgroupdate']);
$tests = Test::where('test_date', '=', $inputDate->format('Y-m-d'))
->orderBy('athlete_id', 'desc')
->get();
}
$request->session()->keep(['tgroupdate']);
//$request->flashOnly(['tgroupdate']);
return view('npr.test_athletes', ['tests' => $tests]);
My view:
<form class="form-inline" role="form" method="POST" action="{{ route('admin.search_tgroup') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="tgroupdate" class="control-label">Test Date</label>
<div class="input-group date" id="testgroupdatepicker">
<input name="tgroupdate" type="text" style="background-color:#ffffff" readonly=""
value="{{ Session::get('tgroupdate') }}" class="form-control">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Search Athletes
</button>
<input type="hidden" name="_token" value="{{ Session::token()}}">
</div>
</form>
You dont need to save the date in session. You can save the date in a variable,send it to the view and in the view you can check if variable exist using isset php function.
In Controller
public function groupTestAthletes(Request $request)
{
$inputDate = null;
$tests = null;
if ($request['tgroupdate']){
$inputDate = Carbon::createFromFormat('d/m/Y', $request['tgroupdate']);
$tests = Test::where('test_date', '=', $inputDate->format('Y- m-d'))
->orderBy('athlete_id', 'desc')
->get();
}
return view('npr.test_athletes', ['tests' => $tests,'selected_date' => $request['tgroupdate']]);
And in the view,
<form class="form-inline" role="form" method="POST" action="{{ route('admin.search_tgroup') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="tgroupdate" class="control-label">Test Date</label>
<div class="input-group date" id="testgroupdatepicker">
<input name="tgroupdate" type="text" style="background-color:#ffffff" readonly=""
value="#if(isset($selected_date)) $selected_date #endif" class="form-control">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Search Athletes
</button>
<input type="hidden" name="_token" value="{{ Session::token()}}">
</div>
</form>
Edit: This minor change in the view gave the optimal solution.
value="#if(isset($selected_date)){{$selected_date}}#endif"

Resources