Laravel 8 - Error Class 'App\Student' not found in StudentController.php - php

hopefully someone can enlighten me on this bug. Laravel 8. I am replicating a simple blog from this url: https://www.codewall.co.uk/laravel-crud-demo-with-resource-controller-tutorial/
It seems like sometimes you do these tutorials but laravel 8 is slightly different. What am I missing here? Any suggestions would be greatly appreciated!
Getting error when going to /students & a /students/create urls , I am getting different errors for
/students (index) error -
Error
Class 'App\Student' not found
It doesn't like the create route either which is weird because I have store method in StudentController.
/students/create (create) error -
Action StudentController#store not defined. (View: C:\xampp\htdocs\laravel\lara-blog2\blog\resources\views\students\create.blade.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Student;
class StudentController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$students = Student::all();
return view('students.index', compact('students','students'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('students.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'age' => 'required|numeric',
'email' => 'required|email',
]);
$input = $request->all();
Student::create($input);
return redirect()->route('students.index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$student = Student::findOrFail($id);
return view('students.show', compact('student','student'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$student = Student::find($id);
return view('students.edit', compact('student','student'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$student = Student::findOrFail($id);
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'age' => 'required|numeric',
'email' => 'required|email',
]);
$input = $request->all();
$student->fill($input)->save();
return redirect()->route('students.index');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$student = Student::findOrFail($id);
$student->delete();
return redirect()->route('students.index');
}
}

As you are using Laravel 8, all models now are located in App\Models directory in App directory as previous versions, so you need to update your import statement to be
use App\Models\Student;
Read more about Models new directory in Laravel Release Notes Here

In Laravel 8, all models now are located in App/Models so use
use App\Models\Student;

From Laravel 8, all models are now located in the App\Models directory in the App directory as in previous versions, so you need to update your import statement to be
App\Models\Student; instead of App\Student;

Related

New blogs not being shown or stored in the database

Once I delete a blog, it is deleted completely. I can make a new one, but it does not show on the website or in the database. This is my BlogController:
<?php
namespace App\Http\Controllers;
use App\Models\Blog;
use Illuminate\Http\Request;
class BlogController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$blog = Blog::paginate(5);
return view('blogs.index', compact('blog'))
->with('i',(request()->input('page',1)-1)*5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('blogs.create');
Blog::create($request->all());
return redirect()->route('blogs.index')
->with('success','Blog created successfully.');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
]);
$blog = new Blog;
$blog->title = $request->title;
$blog->description = $request->description;
$blog->save();
return redirect()->route('blogs.index');
}
/**
* Display the specified resource.
*
* #param \App\Blog $blog
* #return \Illuminate\Http\Response
*/
public function show(Blog $blog)
{
return view('blogs.show', compact('blog'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Blog $blog
* #return \Illuminate\Http\Response
*/
public function edit(Blog $blog)
{
return view('blogs.edit', compact('blog'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Blog $blog
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Blog $blog)
{
$request->validate([
'title' => 'required',
'description' => 'required',
]);
// $blog->title = $request->title;
// $blog->description = $request->description;
$blog->fill($request);
// dd($blog);
return redirect()->route('blogs.index')
->with('success','Blog updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Blog $blog
* #return \Illuminate\Http\Response
*/
public function destroy(Blog $blog)
{
$blog->delete();
return redirect()->route('blogs.index')
->with('success','Blog deleted successfully');
}
}
And the problem is apparently the 103th line, public function update: $blog->fill($request); It does not store in the database nor is it visible on the webpage/blog. I tried deleting that specific line, but it is the same. Nothing changes. I do not understand what the issue could be. Can someone help?
1ST OPTION In order for the fill method to work, you must call $blog->save() after that.
$blog->fill($request);
$blog->save();
Also when you use fill method you are mass assigning values. By default Laravel protects you from mass assigning fields.
Open your Blog.php model and add the fields you want to mass assign to the array $fillable
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'title',
'description',
];
2ND OPTION is to use the update method (don't forget to also add fields in $fillable in the model from 1st option since update method is also mass assigning fields):
$blog->update($request);
3RD OPTION manually assign each field one-by-one just like you did in the store method:
$blog->title = $request->title;
$blog->description = $request->description;
$blog->save();
The fill function dose not update data in database.
This function only assignment value to attribute in protected $fillable = ['title','description']; in Blog model.
Using update function to update data to database.
$blog->fill($request);
$blog->update();

Post array values in mysql database in laravel

I'm developing rest api in laravel, here im trying to post array data in database, but i could not figure out how to do it, can some one guide me in this ? i'm new to laravel
ProductdetaisController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\productdetails;
class ProductdetailsController extends Controller{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return productdetails::all();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'productname' => 'required',
'productid' => 'required',
'productdescription' => 'required',
'productimage' => 'required',
'productinvoice' => 'required',
]);
return productdetails::create($request->all());
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
return productdetails::find($id);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$productdetails = productdetails::find($id);
return $productdetails->update($request->all());
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
return productdetails::find($id)->delete();
}
}
productdetails.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class productdetails extends Model
{
use HasFactory;
protected $fillable = ['productname', 'productid', 'productdescription', 'productimage', 'productinvoice'];
}
2021_09_25_075455_create_productdetails_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductdetailsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('productdetails', function (Blueprint $table) {
$table->id();
$table->string('productname');
$table->string('productid');
$table->string('productdescription');
$table->array('productinvoice'); <----- here i want to store array of data ------>
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('productdetails');
}
}
example for array of data
[{productquantity: '5', productprice: '5', productgst: '5', productname: 'xyz'}, {productquantity: '5', productprice: '5', productgst: '5', productname: 'ABC'}]
How to post such kind of above data in the data base ?
Model::create() doesn't work like that. You should loop over the array and create rows individually.
Laravel docs on this method
Also, your validation won't work. Docs on array validation
Try this: (save it to database)
$productinvoice =json_encode( $request->your_array_json_data );
...save it to database.
When you want to use It inside client side You should parse It to array of json data.
Like this: (use it inside client side part)
JSON.parse($productinvoice)
When You want to use it inside backend part after retrieve it from database.
This is how You could convert it to php array : (use it inside backend part)
$productinvoice = json_decode($productionDetails->productinvoice, true);

"Type error: Too few arguments to function App\Http\Controllers\UserController::create(), 0 passed and exactly 1 expected"

I have a problem with inserting Data into Database. Let's say I have a controller named HeroController and I want to create a new hero object and insert it to my database as a new hero.
My controller contains the following method:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// return response()->json([
// 'name' => 'Abigail',
// 'state' => 'CA'
// ]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6',
]);
}
public function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data[password]),
]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$user = $request->isMethod('put');
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
return response()->json($usere, 201);
}
/**
* 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)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
My routes.php file:
<?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');
});
Route::get('/users/create', 'UserController#create');
This is the error that i got. Type error: Too few arguments to function App\Http\Controllers\UserController::attendance(), 0 passed and exactly 1 expected". I am new to laravel.
You are using a get request to call create function.
Route::get('/users/create', 'UserController#create');
So, you are not passing any data to that controller. Hence the error.
First, you'll want to change the visibility of create and validator:
protected function create(array $data)
And the validator method:
protected function validator(array $data)
Then you'll want to change your /users/create route to a post and to use the store method:
Route::post('/users/create', 'UserController#store');
In your UserController update your store method to:
public function store(Request $request)
{
// validate the request
$validator = $this->validator($request->all());
if ($validator->fails()) {
return response()
->json(422,$validator->errors()->messages());
}
$user = $this->create($request->all());
return response()->json($user, 201);
}
If you need some sort of form to register or create a user, add an additional method in your controller:
public function register()
{
return view('user.register');
}
Then define another get route:
Route::get('/users/register', 'UserController#register');
Route::delete('/file/{id}','FileController#destroy')->name('deletefile');
Hope it will be helpful

Class App\Http|Controllers\ValidateRegistraion does not exist

I have created a form request using php artisan make:request ValidateRegistration. It created a ValidateRegistration.php file under App\Http\Requests\ directory. After this I have made changes in the store() function of my registration controller ie UserController.php, means I have changed it
FROM
public function store(Request $request)
{
// Save the data
User::create(request(['fname','lname','phone','email','password']));
// redirect to home page
return redirect('/registration-success');
}
TO
public function store(ValidateRagistration $request)
{
// Save the data
User::create(request(['fname','lname','phone','email','password']));
// redirect to home page
return redirect('/registration-success');
}
And added use App\Http\Requests\ValidateRagistration; at the top of the UserController.php file. But when I submit the form without filling anything it shows me an error which is Class App\Http\Controllers\ValidateRegistraion does not exist
EDIT
Added UserController.php and ValidateRegistration.php files.
UserController.php
<?php
use App\Http\Requests\ValidateRegistration;
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$title = "Registration";
return view('/registration', compact('title'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(ValidateRegistration $request)
{
//// validate requested data
//$this->validate(request(), [
// 'fname' => 'required',
// 'lname' => 'required',
// 'phone' => 'required|size:10',
// 'email' => 'required',
// 'password' => 'required'
//]);
// Save the data
User::create(request(['fname','lname','phone','email','password']));
// redirect to home page
return redirect('/registration-success');
}
/**
* 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)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
ValidateRegistration.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ValidateRegistration extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'fname' => 'required',
'lname' => 'required',
'phone' => 'required|size:10',
'email' => 'required',
'password' => 'required'
];
}
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [
'fname.required' => 'Firstname is mandatoy',
'lname.required' => 'Lastname is mandatory',
'phone.required' => 'Phone is mandatory',
'phone.size' => 'Phone must be 10 digit',
'email.required' => 'Email is mandatory',
'password.required' => 'Password is mandatory',
];
}
}
spot the difference in your class names:
ValidateRagistration
ValidateRegistraion
and I'm guessing it should read ValidateRegistration, clear up typos, they will only confuse things later
at the top of UserController.php swap the positions of the namespace and use lines, namespace should always be first
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ValidateRegistration;
use Illuminate\Http\Request;
use App\User;
and ValidateRegistration.php is in your App\Http\Requests directory
in ValidateRegistration.php I modified the authorize() function. It was returning false. Changed it to true. It is working now.
From
public function authorize()
{
return false;
}
To
public function authorize()
{
return true;
}

Laravel 5.4 Internal error: Failed to retrieve the default value

I have a form which submits data to the database. And it submits data to the database. But Laravel yields an error when it tries to redirect it to another method in the same controller.
ReflectionException in RouteDependencyResolverTrait.php line 57:
Internal error: Failed to retrieve the default value
Here is the controller I use. Please check the public function store(Request $request) method.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Inbox;
class ContactUsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('pages.contactus');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// validate the data
// store the data in the database
// redirect to another page
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required',
'telephone' => 'required',
'message' => 'required',
]);
$inbox = new Inbox;
$inbox->name = $request->name;
$inbox->email = $request->email;
$inbox->telephone = $request->telephone;
$inbox->message = $request->message;
$inbox->isnew = 1;
$inbox->category = $request->category;
$inbox->save();
// redirects to the route
//return redirect()->route('contactus.show', $inbox->id);
return redirect()->action(
'ContactUsController#show', ['id' => 11]
);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
print_r($id);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
And I tried, both of following methods in two different occasions. But Laravel shows the same error each time.
return redirect()->route('contactus.show', $inbox->id);
return redirect()->action(
'ContactUsController#show', ['id' => 11]
);
And here is the route file web.php.
Route::get('contactus', 'ContactUsController#create');
Route::get('contactus/show', 'ContactUsController#show');
Route::post('contactus/store', 'ContactUsController#store');
I have no idea what cause this problem. Any suggestion will be helpful.
Thanks!
You are passing the id value to the router in the redirect, but you are not telling the router to use this value in the route. Therefore, the router does not know to pass the id value into the show method.
Change the route to look like this:
Route::get('contactus/{id}', 'ContactUsController#show');
Then your redirect should work, and you should be redirected to (using the ID from your example) /contactus/11.
You don't have the $id defined on the route. You can either add that to the route with:
Route::get('contactus/show/{id}', 'ContactUsController#show');
OR
You can pass it as a get parameter and retrieve it in the request:
public function show(Request $request)
{
print_r($request->input('id'));
}
I had same error and it was because there was also parameter $request instead of Request $request

Categories