How do I deal with controller resource in laravel - laravel

I am using the resource tool for my controller and my route but the store method appears not to work. Could you highlight what I did wrong. Is the controller name needs to be the same as the model one? I am confuse
FarmController
<?php
namespace App\Http\Controllers;
use App\Animal;
use Auth;
use Illuminate\Http\Request;
class FarmController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$animal = Animal::all();
return view('farms.index', compact('animal'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$user = Auth::user();
$animal = new Animal();
return view('farms.create', compact('user', 'animal'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store()
{
Animal::create($this->validateRequest());
return redirect('farms.show');
}
private function validateRequest()
{
return request()->validate([
'dateOfBirth' => 'required|date',
'placeOfBirth' => 'required',
'gender' => 'required',
'user_id' => 'required',
]);
}
Animal.php (controller)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Animal extends Model
{
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class);
}}
animals (table)
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAnimalsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('animals', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id')->index();
$table->date('dateOfBirth');
$table->string('gender');
$table->string('placeOfBirth');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('animals');
}
}
create.blade.php
#extends('layouts.app')
#section('title', 'Add Animal')
#section('content')
<div class="row">
<div class="col-12">
<h1>Farm</h1>
</div>
</div>
<h3>Welcome {{ $user->name }} Please Add an animal</h3>
<div class="row">
<div class="col-12">
<form action="{{ url('farms') }}" method="POST">
<div class="form-group">
<label for="dateOfBirth">Date Of Birth: </label>
<input type="date" name="dateOfBirth" class="form-control" placeholder="dd/mm/yyyy">
</div>
<div class="pb-5">
{{ $errors->first('dateOfBirth') }}
</div>
<div class="form-group">
<label for="placeOfBirth">Place Of Birth</label>
<input type="text" name="placeOfBirth" class="form-control">
</div>
<div class="pb-5">
{{ $errors->first('placeOfBirth') }}
</div>
<div class="form-group">
<label for="gender">Gender: </label>
<select name="gender" class="form-control">
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</div>
<div class="form-group">
<label for="user">User</label>
<select class="form-control" name="user">
<option value="{{ $user->id }}" name="user">{{ $user->name }}</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Add Farm</button>
#csrf
</form>
</div>
</div>
#endsection
web.php (routes)
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::middleware('admin')->group(function () {
// All your admin routes go here.
Route::resource('/admin', 'AdminController');
});
Route::middleware('farms')->group(function () {
// All your admin routes go here.
Route::resource('/farms', 'FarmController');
});
When I am submitting the form, it seems like it just refreshes the page and do not add anything in my table. I have been stuck on this in two entire days. any help is welcome

In the validateRequest function you have
'user_id' => 'required',
But your form in the view has no field named user_id
The select element is named user
<select class="form-control" name="user">
<option value="{{ $user->id }}" name="user">{{ $user->name }}</option>
</select>
Change one of them so they can match, I guess that the page refresh is just failed validation
You may want to check for any validation error in your view to find out what's wrong as per the docs
For example
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Hope this helps

Just change your form action then it hit in correct mehtod. Here is the action for your form
{{route('farms.store')}}

Related

BadMethodCallException Call to undefined method App\Models\Categorie::ajoutercategorie()

I code an adding product category system for ecommerce.
i got below error
What should I do to solve this problem?
BadMethodCallException
Call to undefined method App\Models\Categorie::ajoutercategorie()
Did you mean App\Models\Categorie::hasGetMutator() ?
The name of my controller is "CategorieController".This is my store function called sauvercategorie in CategorieController.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Categorie;
class CategorieController extends Controller
{
//
public function ajoutercategorie(){
return view('admin.ajoutercategorie');
}
public function sauvercategorie(Request $request){
$validatedData = $request->validate([
'category_name' => 'required | max:255',
]);
$categorie = Categorie::ajoutercategorie($validatedData);
return redirect('/ajoutercategorie')->with('status', 'La catégorie'
.$categorie->category_name.'a été ajoutée avec succès');
My entire blade file.
#extends('layouts.appadmin')
#section('title')
Ajouter une catégorie
#endsection
#section('contenu')
<div class="row grid-margin">
<div class="col-lg-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Ajouter une catégorie</h4>
#if (Session::has('status'))
<div class="alert alert-success">
{{Session::get('status')}}
</div>
#endif
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="cmxform" id="commentForm" method="post" action="{{ route('categories.sauvercategorie') }}">
#csrf
<fieldset>
<div class="form-group">
<label for="cemail">Nom de la catégorie</label>
<input id="cemail" class="form-control" type="text" name="category_name" >
</div>
<input class="btn btn-primary" type="submit" value="Ajouter">
</fieldset>
</form>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
{{--<script src="Administrateur/js/form-validation.js"></script>
<script src="Administrateur/js/bt-maxLength.js"></script>--}}
#endsection
the name of model is Categorie. This is my model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Categorie extends Model
{
use HasFactory;
protected $fillable = ['category_name'];
}
my table name is "categories". This is my table
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('categorie_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
Need helps to solve that, thanks.
Your controller calling
$categorie = Categorie::ajoutercategorie($validatedData);
which is calling ajoutercategorie function on your Model, but you don't have that function on model.
You can change :
public function sauvercategorie(Request $request){
$validatedData = $request->validate([
'category_name' => 'required | max:255',
]);
$categorie = Categorie::ajoutercategorie($validatedData);
return redirect('/ajoutercategorie')->with('status', 'La catégorie'
.$categorie->category_name.'a été ajoutée avec succès');
into :
public function sauvercategorie(Request $request){
$validatedData = $request->validate([
'category_name' => 'required | max:255',
]);
$categorie = Categorie::create($validatedData);
return redirect('/ajoutercategorie')->with('status', 'La catégorie'
.$categorie->category_name.'a été ajoutée avec succès');
Or you can see this documentation https://laravel.com/docs/9.x/eloquent#inserting-and-updating-models for default function CRUD

How do I get a variable from a table related to the auth user in laravel?

I am working on a project and here are the fields touched
users table-
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->unsignedInteger('role_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
role table-
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
user model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'role_id',
];
public function role(){
return $this->belongsTo(Role::class);
}
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Role model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $guarded = [];
public function users(){
return $this->hasMany(User::class);
}
}
register controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Role;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'role_id' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role_id' => $data['role_id'],
]);
$roles = Role::all();
return compact('user', 'roles');
}
}
and here is my register blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row">
<label for="role" class="col-md-4 col-form-label text-md-right">Role</label>
<select name="role_id" id="role_id" class="form-control">
#foreach($roles as $role)
<option value="{{ $role->id }}">{{ $role->name }}</option>
#endforeach
</select>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
I am getting this error:
Undefined variable: roles (View: /Users/macair13/MeatracProject/resources/views/auth/register.blade.php)
and I have declared roles in my register controller
Please cloud you help me because personally, I am lost
You haven't passed $roles variable in your blade file,
So, fatal error occurs in foreach loop of your blade file,
so to resolve this you have to pass $roles in your blade ,
There many methods to pass $roles to register.blade file.
by override showRegistrationForm() method from below path in your controller
\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php
or pass $roles in method inside above vendor path.
for example:
return view('auth.register')->with($roles,Role::get());//don't forget to use Role model.
Or incase if your $roles is not set use isset() condition before your foreach() in blade file like
#isset($roles)
#foreach($roles as $role)
<option value="{{ $role->id }}">{{ $role->name }}</option>
#endforeach
#endisset
You need to pass the roles to the view, but what you did is when the user is being created, you try to return the roles. They are not needed then.
So just override the showRegistrationForm() method within your register controller, and it should work.
Add this in your RegisterController.
public function showRegistrationForm()
{
$roles = Role::all();
return view('auth.register', compact('roles'));
}
and this:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role_id' => $data['role_id'],
]);
$roles = Role::all();
return compact('user', 'roles');
}
Should be this:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role_id' => $data['role_id'],
]);
}

How do I deal with form in laravel?

I was dealing with forms in laravel, I have written the code but once i click on the button to submit the form it's just reset the page
Here is my view create.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<form action="/p" enctype="multipart/form-data" method="post">
#csrf
<div class="row">
<div class="col-8 offset-2">
<div class="row">
<h1>Add New Post</h1>
</div>
<div class="form-group row">
<label for="caption" class="col-md-4 col-form-label">Post Caption</label>
<input id="caption"
type="text"
class="form-control{{ $errors->has('caption') ? ' is-invalid' : '' }}"
name="caption"
value="{{ old('caption') }}"
autocomplete="caption" autofocus>
#if ($errors->has('caption'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('caption') }}</strong>
</span>
#endif
</div>
<div class="row">
<label for="image" class="col-md-4 col-form-label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#if ($errors->has('image'))
<strong>{{ $errors->first('image') }}</strong>
#endif
</div>
<div class="row pt-4">
<button class="btn btn-primary">Add New Post</button>
</div>
</div>
</div>
</form>
</div>
#endsection
And my PostsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostsController extends Controller
{
public function create(){
return view('posts.create');
}
public function store(){
$data = request()->validate([
'caption' => 'required',
'image' => ['required', 'image'],
]);
Post::create($data);
dd(request()->all());
}
}
my routes web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/p/create', 'PostsController#create');
Route::post('/p', 'PostsController#create');
Route::get('/profile/{user}', 'ProfilesController#index')->name('profile.show');
The validation is not working and every time I click on the button, it resets everything. Kidly Help me sort this out
Post model
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
Change this line in your web.php file, from
Route::post('/p', 'PostsController#create');
to
Route::post('/p/store', 'PostsController#store')->name('p.store');
As you can see in the modification above, you were pointing to the wrong Controller method.
Additionally, it is best practice to use named route.
With the above named route, you can now use the route helper without worrying about the url like this in your form:
<form action="{{ route('p.store') }}" enctype="multipart/form-data" method="post">
</form>
UPDATE 1:
I didn't catch this earlier. Your Controller method must have at least the Request object as parameter in the definition for POST requests. Also update your validation logic.
Update your store() method to this
public function store(Request $request){
$request->validate([
'caption' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg',
]);
Post::create($request->input());
dd($request->all());
}
Observe that you were using the global request helper request() previously. You don't need to do that anymore because the Request object is now passed in as a parameter. Also note that you don't need to pass any actual arguments when you use the route. The argument is automatically passed in by Laravel.
UPDATE 2:
Also, update your Post model with $fillable array
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
protected $fillable = ['caption', 'image'];
public function user(){
return $this->belongsTo(User::class);
}
}
The $fillable array indicate fields in the database that can be assigned using an HTTP request (e.g. from an HTML form).
From the Laravel documentation:
you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.
The problem is in your route. Both your get and post route are going to the controller's create method. Post route will be like
Route::post('/p', 'PostsController#store');

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!');
}
}

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

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

Resources