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

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.

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

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 Update Function Not Running Correct Response

When I attempt to update a record in my Laravel application, it is running the wrong URL causing an error 404. This function was working fine when I was developing locally however now it is hosted on a one.com server, it has stopped working.
edit.blade.php
<form method="POST" action="gins/{{ $gins->id }}">
#method('PATCH')
#csrf
<div class="field">
<label class="label" for="gin">Gin</label>
<div class="control">
<input type="text" class="input" name="gin"
placeholder="Gin" value="{{ $gins->gin }}">
</div>
</div>
<div class="field">
<label class="label" for="size">Bottle Size(ml)</label>
<div class="control">
<input type="text" class="input" name="size"
placeholder="Size (ml)" value="{{ $gins->size }}">
</div>
</div>
<div class="field">
<label class="label" for="price">Price(£)</label>
<div class="control">
<input type="text" class="input" name="price"
placeholder="Price of Gin" value="{{ $gins->price }}">
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button is-success">Update Record
</button>
</div>
</div>
</form>
Route
Route::patch('gins/{gin}', 'PostsController#update')->middleware('auth');
Auth::routes();
Controller
public function update(Request $request, $id)
{
$gins = \App\Gins::findOrFail($id);
$gins->gin = request('gin');
$gins->size = request('size');
$gins->price = request('price');
$gins->save();
return redirect('gins');
}
The URL for the edit page is Laravel/gins/7/edit. When I click the submit button it's returning the URL Laravel/gins/7/gins/7 when it should be redirecting back to Laravel/gins/7.
The 7 in the Url is the record id from the particular record I'm attempting to update.
It's always a bad idea to hardcode urls like that. The following
<form method="POST" action="gins/{{ $gins->id }}">
in a route like laravel/gins/ would evaluate to laravel/gins/gins/7.
Also, routes change all the time in a dynamic web application. For this reason, I'd suggest you to use Named Routes.
For example:
Route::patch('gins/{gin}', 'PostsController#update')
->middleware('auth')
->name('posts.update');
and then change your form action to this:
<form method="POST" action="{{ route('posts.update', ['gin' => $gins->id]) }}">
I would also clean up your update() method a bit.
public function update(Request $request, $id)
{
$gins = \App\Gins::findOrFail($id);
$gins->gin = request('gin');
$gins->size = request('size');
$gins->price = request('price');
$gins->save();
// change this to a named route as well
return redirect('gins');
// or if you just want to return back to the previous page, you can do
// return back();
}

Update image in laravel won't work

I'm trying to update image in my laravel project but it won't save the image, I'm using intervention package
this is the result i use dd
Controller:
public function update(Request $request, $id)
{
//
$this->validate($request, [
'student_name'=>'required|max:50',
'lead_status'=>'required|max:50',
'lead_source'=>'required|max:50',
'avatar' =>'image',
]);
$leads = Lead::findOrFail($id);
$leads->student_name = $request->student_name;
$leads->student_nric = $request->student_nric;
$leads->gender = $request->gender;
$leads->religion = $request->religion;
$leads->race = $request->race;
$leads->date_of_birth = $request->date_of_birth;
$leads->Address = $request->Address;
$leads->last_school_attended= $request->last_school_attended;
$leads->last_grade_completed = $request->last_grade_completed;
$leads->grade_appliying = $request->grade_appliying;
if($request->hasFile('avatar')){
$image=$request->file('avatar');
$filename=time() . '.' . $image->getClientOriginalExtension();
$location=public_path('images/' .$filename);
Image::make($image)->resize(300, 300)->save($location);
$leads->image=$filename;
$leads->save();
}
else{
$leads->save();
session()->flash('notif','Application Saved Successfully');
return view('leads.edit')->with('leads', $leads);
}
}
Edit.Blade View
<div class="row">
<div class="col-sm-4 form-group">
<img src="/uploads/avatars/{{$leads->image}}" style="width:150px;height:150px;border-radius:50px;">
<form enctype="multipart/form-data" action="{{route('leads.update', $leads->id)}}" method="POST" >
{{ csrf_field() }}
{{ method_field('PUT') }}
<label> Upload Image</label>
<input type="file" name="avatar">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
<div class="col-sm-12">
<h4 text-muted>CHILD'S INFORMATION</h3>
<hr>
<div class="row">
<div class="col-sm-4 form-group">
<label>FULLNAME</label>
<input class="form-control" style="text-transform: uppercase;" type="text" name="student_name" value="{{$leads->student_name}}" placeholder="Enter FULLNAME.." autocomplete="off">
</div>
Note: i will always end up null value on my image please point me to a correct tutorial if u have..
......................................................................................................................................
Add a hidden input type with your database variable in your edit blade
and put the value of your hidden input name in else condition to save.
<input type="hidden" name="old_image_name"
value="#if(isset($admin_details)){{$admin_details->image}} #endif"/>

Laravel Cannot retrieve a specific record from a form

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

Resources