New “Metier” is created when editing a “Metier” - laravel

When I try to edit a "Metier", a new "Metier" is created and the old one stays the same. I want to crush the old "Metier" and create a new one just by editing. Here is my code in relation with the edit function.
Controller
public function edit($id)
{
$metier=Metier::find($id);
return view('metier.edit',['libelle_metier'=>$metier]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$metier=Metier::find($id);
return view('metier.edit',['libelle_metier'=>$metier]);
}
View
<div class="form-group">
<label for="">libelle Metier </label>
<input type="text" name ="libelle_metier" class="form-control"value ="
{{$libelle_metier->libelle_metier}}" >
</div>
<div class="form-group">
<input type="submit" value = "enregistrer" class="form-control btn btn-
primary">
</div>
route
Route::get('/metier', 'MetierController#index');
Route::get('/metier/create', 'MetierController#create');
Route::post('/metier', 'MetierController#store');
Route::get('/metier/{id}/show', 'MetierController#edit');
Route::get('/metier/{id}/edit', 'MetierController#edit');
Route::upd('/metier/{id}/update', 'MetierController#update');
Route::delete('/metier/{id}', 'MetierController#destroy')
MetierController.php
public function edit($id)
{
$metier=Metier::find($id);
return view('metier.edit',['libelle_metier'=>$metier]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$metier = Metier::find($id);
$metier->libelle_metier = $request->libelle_metier;
$metier->save();
return back();
}
edit.blade.php
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Metier </h1>
<form action=" {{url ('metier') }}" method="post">
{{csrf_field()}}
<div class="form-group">
<label for="">libelle Metier </label>
<input type="text" name ="libelle_metier" class="form-
control"value ="
{{$libelle_metier->libelle_metier}}" >
</div>
<div class="form-group">
<input type="submit" value = "enregistrer" class="form-control
btn btn-
primary">
</div>
</form>
</div>
</div>
#endsection

That's because you don't even try to update the DB record. Do something like this instead:
public function update(Request $request, $id)
{
Metier::where('id', $id)->update($request->all());
return back();
}
Or without using the mass assignment:
public function update(Request $request, $id)
{
$metier = Metier::find($id);
$metier->libelle_metier = $request->libelle_metier;
$metier->save();
return back();
}
Update
Thanks for sharing the whole form. You're also using POST method instead of PUT. Change the form URL and add this field to the form:
<form action="{{ url('metier/' . $libelle_metier->id . '/update') }}" method="post">
{{ method_field('PUT') }}
Then the update() method will be executed instead of store().
And change the route to put:
Route::put('/metier/{id}/update', 'MetierController#update');
Also, it's a good idea to use Route::resource instead of manually creating the same routes. It will allow you to avoid this kind of errors.
https://laravel.com/docs/5.6/helpers#method-method-field

add {{ method_field('PATCH') }} to your form and change action to named route and pass metier id to it.
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Metier </h1>
<form action="{{ route('metier.update', $libelle_metier->id) }}" method="post">
{{csrf_field()}}
{{ method_field('PATCH') }}
<div class="form-group">
<label for="">libelle Metier </label>
<input type="text" name ="libelle_metier" class="form-
control"value ="
{{$libelle_metier->libelle_metier}}" >
</div>
<div class="form-group">
<input type="submit" value = "enregistrer" class="form-control
btn btn-
primary">
</div>
</form>
</div>
</div>
#endsection
Route file
Route::patch('/metier/{id}/update', 'MetierController#update')->name('metier.update');
Hint: delete all these
Route::get('/metier', 'MetierController#index');
Route::get('/metier/create', 'MetierController#create');
Route::post('/metier', 'MetierController#store');
Route::get('/metier/{id}/show', 'MetierController#edit');
Route::get('/metier/{id}/edit', 'MetierController#edit');
Route::upd('/metier/{id}/update', 'MetierController#update');
Route::delete('/metier/{id}', 'MetierController#destroy')
and either add just it all as a single resource, so that all REST urls will be added in one shot.
this is how should be if its REST specification. read it
REST Resource Naming Guide and here
Route::resource('metier', 'MetierController');
or add it this way instead of resource
Route::get('/metier', 'MetierController#index')->name('metier.index');
Route::get('/metier/create', 'MetierController#create')->name('metier.create');
Route::post('/metier', 'MetierController#store')->name('metier.store');
Route::get('/metier/{id}', 'MetierController#show')->name('metier.show');
Route::get('/metier/{id}/edit', 'MetierController#edit')->name('metier.edit');
Route::patch('/metier/{id}', 'MetierController#update')->name('metier.update');
Route::delete('/metier/{id}', 'MetierController#destroy')->name('metier.destroy');
Learn about Resource Controllers
Controller
public function edit($id)
{
$metier=Metier::find($id);
return view('metier.edit',['libelle_metier'=>$metier]);
}
public function update(Request $request, $id)
{
// do some request validation
$metier=Metier::find($id);
$metier->update($request->all());
return redirect()->route('metier.show', $metier->id);
}
if you are having mass assignment error.
add protected $guarded = []; to the Metier model

Related

Laravel 8 Form Request Validation Redirect to Index page instead same page and show error

On localhost all is good, but when I deploy the application to the server not working. If form request validation fails instead of bringing me back to the same page and showing an error, it redirects me to the index page.
config.blade.php
<form method="POST" action="{{ route('config.update', $config->id) }}">
#csrf
#method('PUT')
<div class="form-group row">
<div class="col">
<label class="col-form-label">Name</label>
<input id="name" type="text" class="form-control" name="name" value="{{ $config->name }}" required>
</div>
</div>
<div class="form-group row mt-3">
<div class="col">
<label class="col-form-label text-md-right">Address</label>
<input id="address" type="text" class="form-control" name="address" value="{{ $config->address }}">
</div>
</div>
<div class="form-group row mt-3">
<div class="col">
<label class="col-form-label text-md-right">Phone</label>
<input id="phone" type="tel" class="form-control" name="phone" value="{{ $config->phone }}" required>
</div>
</div>
<div class="form-group row mt-3">
<div class="col">
<label class="col-form-label text-md-right">E-mail</label>
<input id="email" type="email" class="form-control" name="email" value="{{ $config->email }}" required>
</div>
</div>
<div class="form-group row mt-4 mb-0">
<div class="col-md-12">
<button type="submit" class="btn btn-primary button-full-width">Save changes</button>
</div>
</div>
</form>
web.php
Route::resource('/admin/config', 'Admin\ConfigController');
ConfigController
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Services\ConfigServices;
use App\Http\Requests\ConfigRequest;
use App\Models\Config;
class ConfigController extends Controller
{
protected $configServices;
public function __construct(ConfigServices $configServices) {
$this->middleware('auth');
$this->configServices = $configServices;
}
...
public function update(ConfigRequest $request, $id)
{
$config = $this->configServices->updateConfigById($request, $id);
return redirect()->back();
}
...
}
ConfigRequest - here is the problem
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ConfigRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|string|max:255',
'address' => 'nullable|string|max:255',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:9|max:15',
'email' => 'required|email:rfc',
];
}
}
Form Request return to index page instead same page. On localhost working everything, but when I deploy the app to server a problem arises.
When data on form request validated correct return me back on the same page and show success, but when form request failing redirect mine for some reason to the index page.
A problem arises in Laravel 8, this code worked well in previous Laravel versions.
Can someone help me, please?
In your custom request you need:
/**
* The URI that users should be redirected to if validation fails.
*
* #var string
*/
protected $redirect = '/dashboard';
or
/**
* The route that users should be redirected to if validation fails.
*
* #var string
*/
protected $redirectRoute = 'dashboard';
You can find more in the docs.
In the docs for older versions of Laravel these properties don't exist.
Do you have error parts in your blade?
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#if ($message = Session::get('unique'))
asdsad
#endif
#endforeach
</ul>
</div>
#endif

Laravel Blade Component onclick function

Is it possible on blade component to call a function from onclick, and change its variable value?
public $rental = true;
/**
* Create a new component instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Get the view / contents that represent the component.
*
* #return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
return view('components.product-rental');
}
public function toggleRental(){
$this->rental = !$this->rental;
}
<div class="row">
<div class="col col-md-6">
<div class="form-check form-switch">
<input class="form-check-input" name="rental" type="checkbox" #click="toggleRental()" id="rental" value="1" checked>
<label class="form-check-label" for="rental">Rental</label>
</div>
</div>
</div>
{{$rental}}
Basically, what i want is when i CLICK a button, it will call the "toggleRental()" function from blade component and update the "$rental" variable. Is this possible?
I think you should consider using Livewire instead.
It provides exactly this kind of features.
Otherwise you should implement an API endpoint and use Javascript to do so.
EDIT:
So you can use something like this:
<div class="row">
<div class="col col-md-6">
<div class="form-check form-switch">
<input class="form-check-input" name="rental" type="checkbox" data-rental="{{ $rental }}" onclick="toggleRental" id="rental" value="1" checked>
<label class="form-check-label" for="rental">Rental</label>
</div>
</div>
</div>
{{$rental}}
<script>
document.addEventListener('DOMContentLoaded', (event) => {
var rentalCheckBox = document.querySelector('#rental');
rentalCheckBox.value = rentalCheckBox.getAttribute('data-rental');
function toggleRental(){
rentalCheckBox.value = !rentalCheckBox.value;
}
});
</script>

Trying to get property 'id' of non-object (View: E:\xampp\htdocs\mini_blog\resources\views\admin\posts\edit.blade.php)

Trying to get property 'id' of non-object
how to fix the bug, please explain to me, someone
edit.blade.php
#extends('layouts.app')
#section('content')
<div class="card">
<div class="card-header text-center">Edit Post : {{$posts->title}}</div>
<div class="card-body">
#if(count($errors)>0)
<ul class="list-group alert">
#foreach($errors->all() as $error)
<li class="list-group-item text-danger">
{{$error}}
</li>
#endforeach
</ul>
#endif
<form action="{{route('post.update',['id'=>$posts->id])}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" name="title" placeholder="Enter" class="form-control" value="{{$posts->title}} ">
</div>
<div class="form-group">
<label for="image">Featured Image</label>
<input type="file" name="image" class="form-control">
</div>
<div class="form-group">
<label for="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $cat)
<option value="{{$cat->id}}"
#if($posts->cat->id== $cat->id)
selected
#endif
>{{$cat->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="tag">Select Tags</label>
#foreach($tag as $tags)
<div class="checkbox">
<label><input type="checkbox" name="tags[]" value="{{$tags->id}}"
#foreach($posts->tags as $t)
#if($tags->id==$t->id)
checked
#endif
#endforeach
>{{$tags->tag}}</label>
</div>
#endforeach
</div>
<div class="form-group">
<label for="content">Description</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control"> {{$posts->content}}</textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Submit" class="btn btn-primary">
</div>
</form>
</div>
</div>
#endsection
PostController.php
#extends('layouts.app')
#section('content')
<div class="card">
<div class="card-header text-center">Edit Post : {{$posts->title}}</div>
<div class="card-body">
#if(count($errors)>0)
<ul class="list-group alert">
#foreach($errors->all() as $error)
<li class="list-group-item text-danger">
{{$error}}
</li>
#endforeach
</ul>
#endif
<form action="{{route('post.update',['id'=>$posts->id])}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" name="title" placeholder="Enter" class="form-control" value="{{$posts->title}} ">
</div>
<div class="form-group">
<label for="image">Featured Image</label>
<input type="file" name="image" class="form-control">
</div>
<div class="form-group">
<label for="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $cat)
<option value="{{$cat->id}}"
#if($posts->cat->id== $cat->id)
selected
#endif
>{{$cat->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="tag">Select Tags</label>
#foreach($tag as $tags)
<div class="checkbox">
<label><input type="checkbox" name="tags[]" value="{{$tags->id}}"
#foreach($posts->tags as $t)
#if($tags->id==$t->id)
checked
#endif
#endforeach
>{{$tags->tag}}</label>
</div>
#endforeach
</div>
<div class="form-group">
<label for="content">Description</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control"> {{$posts->content}}</textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Submit" class="btn btn-primary">
</div>
</form>
</div>
</div>
#endsection
Trying to get property 'id' of non-object when I select category its not selected and show id is non-object
PostController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
use App\Post;
use App\Tag;
use Session;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.posts.index')->with('posts',Post::all());
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$categories=Category::all();
if($categories->count()==0){
Session::flash('info','You must have some categories before attempt post.');
return redirect()->back();
}
return view('admin.posts.create')->with('category',$categories)->with('tags',Tag::all());
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'title'=>'required|max:255',
'image'=>'required|image',
'content'=>'required',
'category_id'=>'required',
'tags'=>'required'
]);
$images=$request->image;
$image_new_name=time().$images->getClientOriginalName();
$images->move('uploads/posts',$image_new_name);
$post=Post::create([
'title'=>$request->title,
'image'=>$request->image,
'content'=>$request->content,
'image'=>'uploads/posts/'.$image_new_name,
'category_id'=>$request->category_id,
'slug'=>str_slug($request->title)
]);
$post->tags()->attach($request->tags);
Session::flash('success','Post Created Successfully');
return redirect()->back();
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$post=Post::find($id);
return view('admin.posts.edit')->with('posts',$post)
->with('categories',Category::all())
->with('tag',Tag::all());
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request,[
'title'=>'required',
'content'=>'required',
'category_id'=>'required',
]);
$post=Post::find($id);
if ($request->hasFile('image'))
{
$featured=$request->image;
$featured_new_name=time().$featured->getClientOriginalName();
$featured->move('uploads/posts',$featured_new_name);
$post->image='uploads/posts/'.$featured_new_name;
}
$post->title=$request->title;
$post->content=$request->content;
$post->category_id=$request->category_id;
$post->save();
$post->tags()->sync($request->tags);
Session::flash('success','Your Post Updated Successfully');
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post=Post::find($id);
$post->delete();
Session::flash('success','Post was just trashed');
return redirect()->back();
}
public function trashed(){
$post=Post::onlyTrashed()->get();
return view('admin.posts.trashed')->with('posts',$post);
}
public function kill($id){
$post=Post::withTrashed()->where('id',$id)->first();
$post->forceDelete();
Session::flash('success','Post deleted permanently');
return redirect()->back();
}
public function restore($id){
$post=Post::withTrashed()->where('id',$id)->first();
$post->restore();
Session::flash('success','Post Restore ');
return redirect()->route('posts');
}
}
Make sure that categories, tags are not empty, also the Postrelationships are true.

Can't update Laravel database (Model, View, Controller)

I'm currently working with Laravel. I'm a novice and still trying to get used to the platform. I want to update my database based on form input but it's not working. I've tried updating models, views, and controllers and can't seem to get the database to update with input values.
My view:
<div class="form-group row">
<label class="col-xs-2 col-form-label">Expiration Date</label>
<div class="col-xs-10">
<input class="form-control" type="date" value="{{ $Document->expires_at }}" name="expires_at" placeholder="Expiration Date">
</div>
</div></form>
<embed src="{{ asset('storage/'.$Document->url) }}" width="100%" height="100%" />
<div class="row">
<div class="col-xs-6">
<form action="{{ route('admin.provider.document.update', [$Document->provider->id, $Document->id]) }}" method="POST">
{{ csrf_field() }}
{{ method_field('PUT') }}
<button class="btn btn-block btn-primary" type="submit">Approve</button>
</form>
</div></form>
My model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ProviderDocument extends Model
{
protected $table = 'provider_documents';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'provider_id',
'document_id',
'url',
'unique_id',
'status',
'expires_at',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
];
/**
* The services that belong to the user.
*/
public function provider()
{
return $this->belongsTo('App\Provider');
}
/**
* The services that belong to the user.
*/
public function document()
{
return $this->belongsTo('App\Document');
}
}
My controller:
public function update(Request $request, $provider, $id)
{
if(Setting::get('demo_mode', 0) == 1) {
return back()->with('flash_error', 'Disabled for demo purposes! Please contact us at info#appoets.com');
}
try {
$Document = ProviderDocument::where('provider_id', $provider)
->where('id', $id)
->firstOrFail();
$Document->update(['status' => 'ACTIVE']);
$Document->expires_at = $request['expires_at'];
$Document->save();
return redirect()->route('admin.provider.document.index', $provider)->with('flash_success', 'Provider document has been approved.');
}
catch (ModelNotFoundException $e) {
return redirect()->route('admin.provider.document.index', $provider)->with('flash_error', 'Provider not found!');
}
}
The database stays blank with no errors. If I manually put it in the database directly, then go to the form and update, it's deleted. Please help.
Thanks to the input of ##LimKeanPhang above, below is the end result. I didn't have to change the model or controller. Just the view. Worked like a charm.
<form class="form-horizontal" action="{{ route('admin.provider.document.update', [$Document->provider->id, $Document->id]) }}" method="POST">{{csrf_field()}}
<input type="hidden" name="_method" value="PATCH">
<div class="form-group row">
<label class="col-xs-2 col-form-label">Expiration Date</label>
<div class="col-xs-10">
<input class="form-control" type="date" value="{{ $Document->expires_at }}" name="expires_at" placeholder="Expiration Date">
</div>
</div>
<embed src="{{ asset('storage/'.$Document->url) }}" width="100%" height="100%" />
<div class="row">
<div class="col-xs-6">
<button class="btn btn-block btn-primary" type="submit">Approve</button>
</div>
</div>
</form>
Why don't you get the get the document by id only as follows ? Please try the following code. It should work.
The controller update function.
public function update(Request $request, $provider, $id)
{
if (Setting::get('demo_mode', 0) == 1) {
return back()->with('flash_error', 'Disabled for demo purposes! Please contact us at info#appoets.com');
}
try {
$Document = ProviderDocument::find($id);
$Document->status = 'ACTIVE';
$Document->expires_at = $request['expires_at'];
$Document->save();
return redirect()->route('admin.provider.document.index', $provider)->with('flash_success',
'Provider document has been approved.');
} catch (ModelNotFoundException $e) {
return redirect()->route('admin.provider.document.index', $provider)->with('flash_error',
'Provider not found!');
}
}

Issues with Laravel Mailables

I'm trying to create a contact form in Laravel using Laravel 5.3, but I get this nasty error here:
ErrorException in helpers.php line 519:
htmlspecialchars() expects parameter 1 to be string, object given (View: /Applications/XAMPP/xamppfiles/htdocs/meps/resources/views/emails/contactemail.blade.php)
Here are the files that I was using:
The contact form
<div class="contact-form">
<form class="margin-clear" role="form" action="{{ url('/sendmail') }}" method="POST">
{{ csrf_field() }}
<div class="form-group has-feedback">
<label for="name">Name*</label>
<input type="text" class="form-control" id="name" name="name" placeholder="">
<i class="fa fa-user form-control-feedback"></i>
</div>
<div class="form-group has-feedback">
<label for="email">Email*</label>
<input type="email" class="form-control" id="email" name="email" placeholder="">
<i class="fa fa-envelope form-control-feedback"></i>
</div>
<div class="form-group has-feedback">
<label for="subject">Subject*</label>
<input type="text" class="form-control" id="subject" name="subject" placeholder="">
<i class="fa fa-navicon form-control-feedback"></i>
</div>
<div class="form-group has-feedback">
<label for="message">Message*</label>
<textarea class="form-control" rows="6" id="message" name="message" placeholder=""></textarea>
<i class="fa fa-pencil form-control-feedback"></i>
</div>
<input type="submit" value="Submit" class="btn btn-primary">
</form>
</div>
The Controller function
public function sendmail(Request $request, Mailer $mail) {
$mail->to('kaley36_aw#yahoo.com')->send(new ContactEmail($request->name, $request->email, $request->subject, $request->message));
$request->session()->flash('mail-sent', 'Your email has been sent.');
return redirect('/contact');
}
The Mailable class
class ContactEmail extends Mailable
{
use Queueable, SerializesModels;
public $name;
public $email;
public $subject;
public $message;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($name, $email, $subject, $message)
{
$this->name = $name;
$this->email = $email;
$this->subject = $subject;
$this->message = $message;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from($this->email)->view('emails.contactemail');
}
}
And here is the route
Route::post('sendmail', 'EmailController#sendmail');
You probably looking at the wrong view. The error points to
/views/emails/contactemail.blade.php
But this view has a <form> unless you are sending back to your users a form via e-mail, this looks a lot more like your contact form view and not your e-mail view. Something like:
/views/contact.blade.php (or whatever you have in there as a form)
As for the error, you must have a {{ $variable or functionCall() }} which is not receiving a string, but an object.
I figured it out. The issue was with the variable $message, Laravel wrapped it in an actual object called Message. All I had to do was change the variable name to $theMessage and it worked find.

Resources