I'm trying to make a CRUD (which was working fine in a simple blade) in a new template but it is not showing any page of crud and says not found. If I type: php artisan route:list then it says:
Class App\Http\Controllers\PostsController does not exist
I'm following this tutorial and my folder structure is https://ibb.co/db4WQ8R
Controller
class CrudsController extends Controller
{
public function index()
{
$data = Post::latest()->paginate(5);
return view('adminhome', compact('data'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
public function create()
{
return view('create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'image' => 'required|image'
]);
$image = $request->file('image');
$new_name = rand().'.'.$image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$form_data = array(
'name' => $request->name,
'image' => $new_name
);
Crud::create($form_data);
return redirect('post')->with('success', 'Data Added successfully.');
}
}
Routes
Route::group(['middleware' => ['auth']], function () {
Route::get('/home', function () {
if (Auth::user()->admin === 0) {
return view('home');
}
return view('adminhome');
});
Route::resource('post', 'PostsController');
});
How can I solve it?
In your controller rename Cruds
class PostsController extends Controller
{
Related
I am making a form in laravel 5.8 in which I am trying to save the image in a folder and the path in the database.
But just save the image and not the route, I've been searching and haven't found a solution.
The "uploads" folder (folder where images are saved) is located inside the "public" folder.
This is my controller:
public function store(SaveAssistanceRequest $request)
{
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$name = time().$file->getClientOriginalName();
$file->move(public_path().'/uploads/', $name);
}
$assistance= new Assistance();
$assistance->photo = $name;
Assistance::create($request->validated());
return redirect()->route('assistances.index')->with('status',' Assistance was created successfully.
');
}
This file validates the data
class SaveAssistanceRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'resident_id' => 'required',
'date' => 'required',
'entry_time' => 'required',
'departure_time' => 'required',
];
}
public function messages()
{
return[
'resident_id.required' => 'Assistance needs a resident',
'date.required' => 'Assistance needs a date',
'entry_time.required' => 'Assistance needs one hour of entry',
'departure_time.required' => 'Assistance needs a departure time',
];
}
}
Can anybody help me?
public function store(SaveAssistanceRequest $request)
{
$name='';
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$name = time().$file->getClientOriginalName();
$file->move(public_path().'/uploads/', $name);
}
$assistance=Assistance::create($request->validated());
$assistance->photo = $name;
$assistance->save();
return redirect()->route('assistances.index')->with('status',' Assistance was created successfully.
This is my function :
public function index(Request $request)
{
$data = User::all();
return view('data.index',[
'data' => $data
]);
}
I write a test for this
public function testIndex()
{
$response = $this->call('GET', '/data');
$this->assertEquals(200, $response->status());
}
but not works. Show redirection
Response status code [302] is not a successful status code.
Failed asserting that false is true.
Here is my route:
Route::group(['prefix' => 'data'], function() {
Route::get('/', ['as' => 'data.index', 'uses' => 'DataController#index']);
});
I tried everything but still showing the same thing.
You just need to change your index() method as following :
public function index(Request $request)
{
$data = User::all();
return view('data.index',[
'data' => $data
])->setStatusCode(200);
}
Hope it will helps you. Thanks
I have an asset_category table(columns 'asset_category_id', 'category') and an asset table(columns 'asset_id', 'asset_category_id') and want display the (columns 'asset_id', 'asset_category_id.category,') from the asset table instead of just the 'asset_id' n 'asset_category_id' columns.
Asset_CatoriesController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Asset_category;
class Asset_CategoriesController extends Controller
{
public function asset_category(){
$asset_categories = Asset_category::all();
return view('category', ['asset_categories' => $asset_categories]);
}
public function add(Request $request){
$this->validate($request, [
'asset_category_id' => '',
'category' => 'required'
]);
$asset_categories = new Asset_category;
$asset_categories ->asset_category_id = $request->input('asset_category_id');
$asset_categories ->category = $request->input('category');
$asset_categories ->save();
return redirect('/category') ->with('info', 'New Category Saved Successfully!');
}
public function update($id){
$asset_categories = Asset_category::find($id);
return view('update', ['asset_categories' => $asset_categories]);
}
public function edit(Request $request, $id){
$this->validate($request, [
'asset_category_id' => '',
'category' => 'required'
]);
$data = array(
'category' => $request ->input('category')
);
Asset_category::where('asset_category_id', $id)->update($data);
return redirect('/category') ->with('info', 'Category Updated Successfully!');
}
public function delete($id){
Asset_category::where('asset_category_id', $id)
->delete();
return redirect('/category') ->with('info', 'Category Deleted Successfully!');
}
}
AssetController
<?php
namespace App\Http\Controllers;
use App\Asset;
use App\Asset_category;
use App\Manufacturer;
use App\Department;
use Illuminate\Http\Request;
class AssetController extends Controller
{
public function asset(){
$assets = Asset::all();
// return view::make('viewAsset')->with('assets', $assets);
return view('viewAsset', ['assets' => $assets]);
}
public function manufacturer(){
$manufacturers = Manufacturer::all();
return view('asset', ['manufacturers' => $manufacturers]);
}
public function add(Request $request){
$this->validate($request, [
'asset_id' => '',
'asset_category_id' => 'required',
'manufacturer_id' => 'required',
'department_id' => 'required',
]);
$assets = new Asset;
$assets ->asset_id = $request->input('asset_id');
$assets ->asset_category_id = $request->input('asset_category_id');
$assets ->manufacturer_id = $request->input('manufacturer_id');
$assets ->department_id = $request->input('department_id');
$assets ->save();
return redirect('/viewAsset') ->with('info', 'New Asset Saved Successfully!');
}
public function update($id){
$assets = Asset::find($id);
return view('updateAsset', ['assets' => $assets]);
}
public function edit(Request $request, $id){
$this->validate($request, [
'asset_id' => '',
'asset_category_id' => 'required',
'manufacturer_id'=> 'required',
'department_id' => 'required'
]);
$data = array(
'asset_category_id' => $request ->input('asset_category_id'),
'manufacturer_id' => $request ->input('manufacturer_id'),
'department_id' => $request ->input('department_id')
);
Asset::where('asset_id', $id)->update($data);
return redirect('/viewAsset') ->with('info', 'Asset Updated Successfully!');
}
public function delete($id){
Asset::where('asset_id', $id)
->delete();
return redirect('/viewAsset') ->with('info', 'Asset Deleted Successfully!');
}
}
Asset.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Asset_category;
class Asset extends Model
{
protected $primaryKey = 'asset_id';
public function category(){
return $this->belongsTo('Asset_category');
//$this->belongsTo('Asset_category');
//Asset_category::where('asset_category_id', $this->asset_category_id)->first()->category;
}
}
Asset_category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Asset;
class Asset_category extends Model
{
protected $primaryKey = 'asset_category_id';
public function asset() {
return $this->hasMany('Asset', 'asset_category_id');
}
}
viewAsset.php
#foreach($assets->all() as $asset)
<tr>
<td>{{ $asset->asset_id}}</td>
<td>{{ $asset->category->category}}</td>
when i run the project i get a FatalErrorExeception which says
Class 'Asset_category' not found in HasRelationships.php
You have Asset_category in a namespace. Try changing this:
return $this->belongsTo('Asset_category');
to this:
return $this->belongsTo(Asset_category::class);
You must end #foreach with #endforeach
You must declare protected $table = 'table_name'; in model because in default laravel generate table name to plural form of model's class name
Try to return this:
return $this->belongsTo('Asset_category');
return $this->hasMany('Asset', 'asset_category_id');
to this:
return $this->belongsTo(Asset_category::class);
return $this->hasMany(Asset::class, 'asset_category_id');
So i have three forms on one page. One is to change user's picture, another one is to update personal informations, and the last form is to set a new password.
My issue here is that i'm getting validation errors on the password and password confirmation fields even though i'm trying to update some information (second form).
I have created two requests:
UserEditRequest:
class UserEditRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'firstname' => 'required',
'lastname' => 'required'
];
}
}
UserUpdatePasswordRequest:
class UserUpdatePasswordRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'password' => 'required|confirmed|min:6',
'password_confirmation' => 'required|min:6',
];
}
}
within UserController updatePassword:
public function updatePassword(UserUpdatePasswordRequest $request, $id)
{
$user = User::findOrFail($id);
$user->password = bcrypt($request->get('password'));
$user->save();
return redirect()->route('user.edit',$id)->with('success','Password changed.');
}
postEdit where I handle the personal details and avatar changes:
public function postEdit(UserEditRequest $request, $id)
{
dd($request->all());
$user = User::findOrFail($id);
if($request->get('avatar'))
{
$destinationPath = public_path() . '/avatars/' . $user->id . '/';
$fileName = $user->id . '.' . $request->file('avatar')->getClientOriginalExtension();
$request->file('avatar')->move($destinationPath, $fileName);
$user->avatar = 'avatars/' . $user->id . '/' . $fileName;
$user->save();
return redirect()->route('user.edit',$id)->with('success','User avatar modified.');
}
$user->fill($request->input())->save();
return redirect()->route('user.edit',$id)->with('success','User details modified.');
}
quicky my routes:
Route::group(['prefix' => 'user', 'as' => 'user.'], function () {
Route::get('profile/{userid}', ['as' => 'edit', 'uses' => 'UserController#getEdit']);
Route::post('profile/{userid}', ['as' => 'edit', 'uses' => 'UserController#postEdit']);
Route::post('profile/{userid}', ['as' => 'updatepassword', 'uses' => 'UserController#updatePassword']);
});
});
Try to differentiate your routes for the postEdit and the updatePassword controller actions
Route::post('profile/{userid}', ['as'=>'edit', 'uses'=>'UserController#postEdit']);
Route::post('profile/password/{userid}', ['as'=>updatepassword', 'uses'=>'UserController#updatePassword']);
Using the same route for two different controller actions won't work. What I mean is how do you expect the router to determine which controller action to invoke when the form action='/profile/id' method='post' ? Hence you need to differentiate the routes.
Hope you got it.
I am trying to make validation with Laravel 5 on right way:
Here is my working code in model:
public function apiAddNewComment() {
if (Input::get("task") == 'addComment') {
$user = Auth::id();
$inputs = array(
'comment' => Input::get('comment'),
'projectID' => Input::get('projectID'),
'order' => Input::get("order"),
'level' => Input::get("level"),
);
$rules = array(
'comment' => 'required|between:15,600',
'projectID' => "required|exists:project_group,project_id,user_id,$user|numeric",
'order' => "required|numeric",
'level' => "required|numeric"
);
$validator = Validator::make($inputs, $rules);
if ($validator->fails()) {
return json_encode(array('err' => true, 'errors' => $validator->messages()->all()));
} else {
return $this->createNewComment();
}
}
}
here is my controller:
public function update($id, Comment $update)
{
return $update->apiUpdateComment();
}
How can I make validation with request?
And can someone explain me how this method works inside request:
public function authorize()
{
return false;
}
?
The Request has to basic functions: rules() and authorize()
rules returns an array that is used for the validation.
The authorize method can for example check if the user is allowed to do this request.
public function authorize() {
return Auth::check();
}
So you don't have to check it each time when you use the request in a controller.
If you need no check just return true.
UPDATE:
Generate a request File with artisan
php artisan make:request CommandRequest
then edit the generate file like this:
class CommandRequest extends FormRequest
{
public function rules()
{
return [
'comment' => 'required|between:15,600',
'projectID' => "required|exists:project_group,project_id,user_id,$user|numeric",
'order' => "required|numeric",
'level' => "required|numeric"
];
}
public function authorize()
{
return true;
}
}
Also update the controller method:
public function update($id, Comment $update, CommandRequest $request)
{
// create your comment here like:
return Comment::create($request->all());
}
You are using a Laravel 4 code I guess, you need to translate it to L5 where Input::get('var') turns into $request->input('var') for instance:
public function apiAddNewComment(Illuminate\Http\Request $request) { //Remember to add the Request as a parameter of the method
if ($request->input("task") == 'addComment') {
...
Then the validation part looks fine