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

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

Related

Laravel 8: Attempt to read property "id" on null

I am facing this error 'Attempt to read property "id" on null' in Laravel 8. It was working fine before but in my view I changed $user->id to $user->profile->id and now this is happening. I am logged in the app and I have changed my route accordingly to match profile id, I have also tried clearing cache etc.
Here is my Code:
User Model:
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
// protected $fillable = [
// 'name',
// 'email',
// 'password',
// ];
protected $table = 'users';
protected $guarded = [];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
public function posts ()
{
return $this->hasMany(Post::class);
}
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Profile Model:
class Profile extends Model
{
use HasFactory;
protected $table = 'profiles';
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
}
ProfilesController:
class ProfilesController extends Controller
{
public function show(User $user)
{
return view ('profiles.index', compact('user'));
}
public function edit(User $user)
{
return view ('profiles.index', compact('user'));
}
}
Route:
Route::get('profile/{profile}', [ProfilesController::class, 'show'])->middleware('auth');
Route::get('profile/{profile}/edit', [ProfilesController::class, 'edit'])->middleware('auth');
View:
<x-layout>
<section class="py-8 max-w-4xl mx-auto">
<h1 class="text-lg font-bold mb-8 pb-2 border-b">
#if ($user->id == auth()->user()->id)
Hello {{ $user->name }}, welcome to your profile.
#else
{{ $user->name }}'s Profile.
#endif
</h1>
<div class="flex">
<aside class="w-48 flex-shrink-0">
<h4 class="font-semibold mb-4">
Navigation
</h4>
<ul style="max-width: 75%">
<li>
View Profile
</li>
<li>
#if ($user->id == auth()->user()->id)
Edit Profile
#endif
</li>
</ul>
</aside>
<main class="flex-1">
<x-panel>
<div class="flex flex-col">
<div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
<div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
<div class="flex flex-row grid-cols-12">
<div class="flex flex-col col-span-4 row-span-full justify-items-start flex-grow-0 flex-shrink-0 grid-cols-4">
<div class="flex flex-row">
<img src="http://i.pravatar.cc/60?u={{ $user->profile->id }}" alt="" width="" height="" class="rounded-full h-24 w-24 flex m-2">
</div>
</div>
<div class="flex flex-col col-span-8 justify-right grid-cols-8 text-sm">
<div class="flex flex-row">
<div class="flex flex-col col-span-2 font-semibold">
<div class="pt-3">Name:</div>
<div class="pt-3">Email:</div>
<div class="pt-3">About:</div>
</div>
<div class="flex flex-col col-span-10">
<div class="pt-3 pl-4 text-justify">{{ $user->profile->name }}</div>
<div class="pt-3 pl-4 text-justify">{{ $user->profile->email }}</div>
<div class="pt-3 pl-4 text-justify"><p>{{ $user->profile->description }}</p></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</x-panel>
</main>
</div>
</section>
I think the problem is that you are passing a Profile model as indicated by your routes, but the method is looking for a User model.
Show and Edit have a User Model as a parameter. If you pass the Profile id, the method is gonna find the User model by id but with the id of the Profile model and not the user_id of the Profile model.
You will need to change the methods to:
public function show(Profile $profile)
{
$user = $profile->user;
return view ('profiles.index', compact('user'));
}
public function edit(Profile $profile)
{
$user = $profile->user;
return view ('profiles.index', compact('user'));
}
With this code the Profile model is found and via the relationship the User is obtained and passed to the view.
public function edit($id)
{
$table = Table::find($id);
return view('tables.edit', compact('table'));
}
public function update(Request $request, $id)
{
$table = Table::find($id);
$table->update($request->all());
return redirect('/tables');
}

How do I deal with controller resource in 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')}}

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

Error while submitting form Laravel 5.6

I have code in router:
/**************Quản lý user*****************/
Route::get('admin/manage-user', 'UserController#getList')->middleware('admin');
Route::get('admin/manage-user/add', 'UserController#indexAdd')->middleware('admin');
Route::post('admin/manage-user/add', 'UserController#getAdd')->middleware('admin');
Code in UserController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Http\Requests\AddUserRequest;
class UserController extends Controller
{
//
public function getList()
{
$data = User::paginate(10);
return view('admin.manage-user',['data' => $data]);
}
public function indexAdd()
{
return view('admin.add-user');
}
public function getAdd(AddUserRequest $request)
{
if($request->fails())
return view('admin.add-user')->withInput();
}
}
Code in AddUserRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AddUserRequest 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 [
'username' => 'required|max:200',
'email' => 'required|email|unique:users',
'pass1' => 'required|min:6',
'pass2' => 'required|same:pass1',
];
}
}
Code view errors:
#extends('layouts.admin')
#section('title','Add User')
#section('content')
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Add User</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form" action="{{url('admin/manage-user/add')}}" method="post">
<div class="box-body">
<div class="form-group">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
When running the path: http://localhost/LBlog/public/admin/manage-user/add and submit (Do not enter form information), the screen returns error: The page has expired due to inactivity. Please refresh and try again.
I hope someone can help me with this issue
That error appears due to CSRF token.
Add csrf token in your form.
<form role="form" action="{{url('admin/manage-user/add')}}" method="post">
#csrf
<div class="box-body">
<div class="form-group">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>

Laravel 5.2 controller index returns blank page

I created a route to a simple contact page. I use a controller to save the data in the database and display them on the same page. When I submit the form I get a blank page but I want the user to stay on the contact. I tried to pass the index view but then I get errors.
The files are
route.php
Route::get('contact', 'ContactController#index');
Route::post('contact', 'ContactController#create');
ContactController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Contact;
class ContactController extends Controller
{
public function index() {
$contacts = Contact::orderBy('created_at', 'asc')->get();
return view('/contact', [ 'contacts' => $contacts ]);
}
public function create(Request $request) {
$name = $request->input('name');
$contact = new Contact;
$contact->name = $name;
$contact->save();
#return view('/contact');
}
}
Contact.php
<?php
Namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $fillable = ['name'];
}
?>
contact.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Contact page</div>
<div class="panel-body">
{!! Form::open(array('url' => 'contact')) !!}
{!! Form::label('name', 'Name') !!}
{!! Form::text('name'); !!}
{!! Form::submit('Submit'); !!}
{!! Form::close() !!}
#if (count($contacts) > 0)
#foreach ($contacts as $contact)
{{ $contact->name }}
#endforeach
#endif
</div>
</div>
</div>
</div>
</div>
#endsection
Try to put contact.blade.php inside views folder and use view('contact', [...]) instead of view('/contact');, you don't need the slash and add return back() to create method:
public function create(Request $request) {
$name = $request->input('name');
$contact = new Contact;
$contact->name = $name;
$contact->save();
return back();
}

Resources