Deleting or Updating posts in LARAVEL using controller - php

{!! Form::open(['action'=>['PostsController#update',$post->id],'method'=>'POST']) !!}
<div class="form-group">
{{Form::label('title', 'Title')}}
{{Form::text('title', $post->title,['class'=>'form-
control','placeholder'=>'Title'])}}
</div>
<div class="form-group">
{{Form::label('body', 'Body')}}
{{Form::textarea('body', $post->body,['id'=>'article
ckeditor','class'=>'form-control','placeholder'=>'Body Text'])}}
</div>
{{Form::hidden('_method','PUT')}}
{{Form::submit('Update',['class'=>'btn btn-success'])}}
{!! Form::close() !!}
I am using this {{ Form::hidden('_method','PUT') }} to update my post because there is no other way. Is there any better way or not?
Here is my controller (postcontroller):
public function update(Request $request, $id)
{
$this->validate($request,[
'title' => 'required',
'body' => 'required'
]);
$post = Post::find($id);
$post->title = $request->title;
$post->body = $request->body;
$post->save();
return redirect('/posts')->with('success','Post Updated Sucessfully');
}

This is the default and correct way to use UPDATE form. You have to use POST in form method and PUT as request parameter (hidden) with form.
What you missed here is CSRF token in form, which can be used in multiple ways like:
{!! Form::token() !!}
{!! Form::hidden('_token', Session::token()) !!}
{!! csrf_field() !!}
#csrf <!-- since Laravel 5.6 -->
Similarly, you can use PUT as:
#method('PUT')

Related

Fetch an id from pivot table to use in form builder in laravel

I need help to access foreign id in my pivot table to use in form builder select form. I'm trying to create a form when I insert movie and select category then they will be connected when I insert it by fetching category_id from pivot table.
I use many to many relationship and my tables are movies and categories with pivot table category_movie (id, category_id, movie_id).
This is my controller and form.
Controller
public function store(Request $request)
{
$request->user()->authorizeRoles('admin');
Movie::create($request->all());
$categories = Category::pluck('category_name', 'id')->all();
return view('movies.upload', compact('movies', 'categories'));
}
View
<div class="col-md-6">
{{csrf_field()}}
{!! Form::open(['method'=>'GET', 'action'=> 'MoviesController#store']) !!}
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label ('', 'Category:') !!}
{!! Form::select('', [''=>'Choose Categories'] + $categories, null, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Insert Movie', ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
</div>
First of all you don't need csrf_field() call (Form::open will inject one for you). All you need to do is add logic to your controller to process selected categories. Give your select a name and make it of type multiple (since you have many to many relationship you want user to be able to select multiple categories for a movie):
<div class="form-group">
{!! Form::label('categories', 'Category:') !!}
{!! Form::select('categories', $categories, null, ['class'=>'form-control', 'multiple' => true]) !!}
</div>
Then in your controller when storing new movie you can read selected 'categories' from the request and attach them:
$movie = Movie::create($request->all());
$movie->categories()->attach($request->get('categories'));
Also store() method is usually accessed via POST route and it returns redirect response to a page where user can view newly created movie (or all movies). To display the form it is better to create a seperate create() method accessed via GET route. And don't forget about validating info in Request - you should either utilize Laravel's FormRequest or use controller's $this->validate() method before inserting anything in your DB.

Laravel. Edit user with relationship

I want make form edit user. For the present moment I can edit the data from the user table, but I would like to assign power to the user roles, from the table roles (dropdownlist).
Controller
public function index()
{
$users = User::with('roles')->get();
return view('pages.user', compact('users'));
}
public function update($id, Request $request)
{
$user = User::with('roles')->findOrFail($id);
$user->update($request->all());
return redirect('users');
}
Form
{!! Form::model($user, ['method' => 'PATCH', 'action'=>['UsersController#update', $user->id]]) !!}
<div class="form-group">
<div class="form-group">
{!! Form::label('name','Name: ') !!}
{!! Form::text('name', null, ['class'=>'form-control','placeholder'=>'Here, user name']) !!}
</div>
<div class="form-group">
{!! Form::label('roles','Roles: ') !!}
{!! Form::select('roles',['class'=>'form-control']) !!}
{!! Form::select('roles',$user,null,['class'=>'form-control']) !!}
//i try this but still not working
</div>
</div>
Thx for help.
I think you want display all role into 'Role' droppdown, check below change of code:
Controller
public function index()
{
//Get user detail
$users = User::with('roles')->get();
//Get all roles
$userRole = Roles::lists('name','id');
return view('pages.user', compact('users', 'userRole'));
}
Form
<div class="form-group">
{!! Form::label('roles','Roles: ') !!}
{!! Form::select('roles',$userRole, null,['class'=>'form-control']) !!}<!-- replace with $users['role_id'], if want to display selected role-->
</div>
NOTE: use pluck instead of list for laravel >= 5.3. The lists method on the Collection, query builder and Eloquent query builder objects has been renamed to pluck. The method signature remains the same.
Let me know if still not working!

Check if Form method is post or patch in Laravel

I have an edit view and i am using a partial _form view.
Is there a way to check if the form is a patch or post?
What i plan to do is to change the hidden field in edit form
#if (form is post)
{!! Form::hidden('signature') !!}
#else
<div class="form-group">
{!! Form::label('signature', 'Signature: ', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::text('signature', null, ['class' => 'col-md-2 form-control', 'required']) !!}
</div>
</div>
#endif
because this variable is already saved to DB and i want to load it for edit.
Or to check if form is post, that would work also!
I usually pass the variable to a view where I set action, like:
$action = 'store';
Then I use this variable to build route name:
{!! Form::open(['route' => 'post'.$action, ....
And detect what type of action is needed:
#if ($action == 'store')
I guess it's the most readable and simple way to achieve what you're trying to achieve. You can do something similar.
Try this:
$isPut= Request::isMethod('put');
if($isPut) {
//
}

Laravel deleting a file NotFoundHttpException

this is my form in my view
{!! Form::open(['url' => ['documents/{file}/{id}', $file->name, $file->id],'method' => 'delete']) !!}
{!! Form::token() !!}
{!! Form::submit('Delete') !!}
{!! Form::close() !!}
controller in which i delete file from database and the original file
public function destroyFile($file_name, $id)
{
File::findOrFail($id)->delete();
$file_path = storage_path('documents').'/'.$file_name;
$destinationPath = $file_path; File::delete($file_path);
return redirect('/documents');
}
This is the route
Route::delete('documents/{file}/{id}','FilesController#destroyFile');
And when i press submit button I get NotFoundHttpException
Try to use this
{!! Form::open(['method' => 'DELETE', 'action' => ['FilesController#destroyFile', $file->name, $file->id] ]) !!}
Actually, their answers are correct. You need the _method to be DELETE. When I am using this. Laravel do it for me.
Or you can put this on your form
<input type="hidden" name="_method" value="DELETE">
or
{!! Form::hidden('_method', 'DELETE') !!}
It is not possible to use this method with html forms in most browsers, most only support GET and POST.
So the reason for this request not working is because the browser sends this as a GET request, wich is the default.
GET, POST, PUT and DELETE are however supported in most major browsers when using XMLHttpRequests (ajax).
add {{ method_field('DELETE') }} to your form .
{!! Form::open(['url' => ['documents/{file}/{id}', $file->name, $file->id],'method' => 'delete']) !!}
{{ method_field('DELETE') }}
{!! Form::token() !!}
{!! Form::submit('Delete') !!}
{!! Form::close() !!}
The reason is that HTML forms does not support PUT, PATCH, DELETE actions. Basically you need to spoof them as described here. https://laravel.com/docs/5.2/routing#form-method-spoofing

Laravel 5 - inserting old data into form via variable

I have a slight problem. I have a system whereby I can drag and drop my own forms. The html code for a form is saved in my database. When it comes to the edit page, I do something like the following
{!! Form::model($project->document, [
'class'=>'form-horizontal',
'method' => 'PATCH',
'route' => ['projects.documents.update', $project, $document->id]
]) !!}
{!! $documentData->documentData !!}
<div class="form-group">
{!! Form::submit('Save Data', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
$documentData->documentData contains the html code for this particular form.
Now my problem is, $documentData->form_data contains the old inputs for this form.
Is there any way to get this old input into the form, the way I am currently handling things?
Thanks
in controller you can access old input by $request->flash(); while in frontend you can access old by input type="text" name="name" value="{{ $name }}"

Categories