New blogs not being shown or stored in the database - php

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

Related

Laravel 8 - Error Class 'App\Student' not found in StudentController.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;

Laravel Spatie unable to restrict UserController

Currently I have users.index blade which I would like to restrict. However, I failed to restrict it.
I have tried to create another test blade and a TestController and I have set permission to it and it works fine.
However with UserController, there is just no way to restrict Users from accessing it:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use DB;
class TestController extends Controller
{
/**
* Restricting pages
*/
public function __construct()
{
$this -> middleware('permission:test-list', ['only' => ['index']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('test.index');
}
/**
* 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)
{
//
}
/**
* 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)
{
//
}
}
views/test/index.blade.php
#extends('layouts.app')
#section('content')
<p>Testing Page</p>
#endsection
These are the results if I don't permit a particular user role to access this page.
enter image description here
enter image description here
So the above is the correct behavior.
However when it comes to user.index , I applied the same technique in the constructor of the UserController but it doesn't work
app/Http/Controllers/UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
class UserController extends Controller
{
public function construct()
{
$this -> middleware('permission:user-list', ['only' => ['index']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = User::orderBy('id','DESC') -> paginate(5);
return view('users.index' , compact('data')) -> with('i' , ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$roles = Role::pluck('name','name') -> all();
return view('users.create',compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request -> all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$user -> assignRole($request -> input('roles'));
return redirect() -> route('users.index') -> with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
return view('users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
$roles = Role::pluck('name','name') -> all();
$userRole = $user->roles -> pluck('name','name') -> all();
return view('users.edit',compact('user','roles','userRole'));
}
/**
* 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, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if( ! empty($input['password'])) {
$input['password'] = Hash::make($input['password']);
} else {
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user -> update($input);
DB::table('model_has_roles') -> where('model_id',$id) -> delete();
$user -> assignRole($request -> input('roles'));
return redirect() -> route('users.index') -> with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
User::find($id) -> delete();
return redirect() -> route('users.index') -> with('success','User deleted successfully');
}
}
Result [I am still able to view this Blade in front end despite not having the permission to view this page]
enter image description here
This is my role-has-permission tablerole-has-permission
This is my role table
role
This is my permission table
permissions
This is my model-has-roles table model-has-roles
This is my model-has-permissions table model-has-permissions
If you want to restrict specific routes or all you can do something like this:
Route::middleware(['auth', 'permission:user-list'])->group(function (){
Route::get('/create', 'WelcomeController#create')->name('welcome');
...
...
..
});
or you can replace
public function construct()
{
$this -> middleware('permission:user-list', ['only' => ['index']]);
}
to
public function construct()
{
$this -> middleware('permission:user-list')->except(['index']);
}

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

Route Not found exception in laravel 5.3 tried resource route and manual route as well

I created a resource BrandController and then made its routes. The problem is that some routes are working and some are not. For example, create route is not working. I have also tried it to declare routes manually but problem is same. I ran command like
php artisan route:clear
php artisan cache:clear
Here are routes
Route::group(['namespace' => 'AppControllers'], function () {
/*
|--------------------------------------------------------------------------
| All routes of BrandController are defined here
|--------------------------------------------------------------------------
|
*/
Route::get('brands', 'BrandController#index')->name('brand.index');
Route::get('brand/create', 'BrandController#create')->name('brand.create');
Route::get('brand/edit/{id}', 'BrandController#edit')->name('brand.edit');
Route::delete('brand/delete/{id}', 'BrandController#destroy')->name('brand.destroy');
Route::post('brand/store', 'BrandController#store')->name('brand.store');
Route::post('brand/update/{id}', 'BrandController#update')->name('brand.update');
// Here is resource route
Route::resource('brands', 'BrandController');
});
I have created a simple a tag here it is:
Add New
Whenever I click on this link it converts / into dotlike this
http://localhost:8080/rms/public/brands.create
It also generated
http://localhost:8080/rms/public/brand/create
But same issue persists. NotFoundHttpException in RouteCollection
Controller Code:
<?php
namespace App\Http\Controllers\AppControllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Brand;
class BrandController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//dd('jgh');
//$brands = brand::all();
return view('brands.index');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return redirect('brands.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(BrandRequest $request)
{
$input = $request->all();
$storeBrand = new Brand();
$storeBrand->create($input);
//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)
{
$editBrand = Brand::findOrFail($id);
return view('brands.edit',compact('editBrand'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(BrandRequest $request, $id)
{
$updateBrand = Brand::findOrFail($id);
$input = $request->all();
$updateBrand->update($input);
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$deleteBrand = Brand::findOrFail($id);
$deleteBrand->delete();
return redirect()->back();
}
}
Change your create method like below
public function create()
{
return redirect('brands/create');
}
. notation not works in redirect method...
Make your resource routes like this
Route::resource('brand', 'BrandController', [
'names' => [
'index'=>'brand.list',
'create'=>'brand.create',
'store'=>'brand.store',
'update'=>'brand.update',
'edit'=>'brand.edit',
'show'=>'brand.show',
'destroy'=>'brand.remove',
]
]);
Your can use:
public function create()
{
return redirect()->route('brands.create');
}
Or
public function create()
{
return redirect('brands/create');
}
But I am suggesting you use the first one because in that we are using route name in that. if you want to change url them you don't have to worry about this code.

laravel route and controller

i am a new laravel user and a have admin page which doing update delete and insert my problem is i dont know how to call this functions in route.
Note: all this options working on one page (admin).
so please can anyone help me ?!
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use DB;
class BlogPostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(){
$date = date('Y-m-d');
$time = time('H:i:s');
/*$sections = ['History' => 'history.png','Electronics' => 'electronics.png','Electrical' => 'electrical.png','Science' => 'science.png',
'Art'=>'ARt.png','Database'=>'database.png','Irrigation'=>'irrigation.png','Novel'=>'Novel.png','Style'=>'Stsyle.png'];
*/
$sections = DB ::table('sections')->get();
return view('libraryViewsContainer.library')->withSections($sections)->withDate($date)->withTime($time);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create(){
//return View::make('posts.create');
return '<center><h1>Creating new section in the library!</h1></center>';
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store( Request $request){
$section_name = $request->input('section_name');
$file = $request->file('image');
$destinationPath = 'images';
$filename = $file->getClientOriginalName();
$file->move($destinationPath,$filename);
DB ::table('sections')->insert(['section_name'=>$section_name,'image_name'=>$filename]);
return redirect('admin');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id){
// $post = Post::find($id);
// return View::make('posts.show')->with('post', $post);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id){
// $post = Post::find($id);
// return View::make('posts.edit')->with('post', $post);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id,Request $request){
$section_name = $request->input('section_name');
DB ::table('sections')->where('id',$id)->update(['section_name'=>$section_name]);
return redirect('admin');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id){
DB :: table('sections')->where('id',$id)->delete();
return redirect('admin');
}
public function admin()
{
$sections = DB ::table('sections')->get();
return view('libraryViewsContainer.admin',['sections'=>$sections]);
}
}
Not entirely sure of the question, but you list the routes in routes.php, under the web group (so it applies default checks).
When you have resources, they'll use CRUD operations (create, read, update, delete) and will correspond to the default operates in the class. Else, make your own function names, and put seperate routes.
Route::group(['middleware' => ['web', 'auth']], function () {
Route::resource('/user', 'UserController');
}
Another option is calling the method direct in your routes:
Route::get('/auth/login', '\App\Http\Controllers\Auth\AuthController#getLogin');
Route::any('/datafeed/{id}/validate', 'DataFeedController#validateQuery');
You'll notice {id} which is the variable available in the function you've selected i.e. function validateQuery($id);
Here's a full example:
class UserController extends BaseController
{
public function __construct(User $model)
{
parent::__construct($model);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$collection = $this->model->all();
return view('user.index')->with('collection', $collection);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('user.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = Input::except(['_method', '_token']);
$connector = $this->model->create($input);
return redirect()->action('UserController#show', [$connector->id]);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$connector = $this->model->findOrFail($id);
return view('user.show')->with('connector', $connector);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$connector = $this->model->findOrFail($id);
return view('user.edit')->with('connector', $connector);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$input = Input::except(['_method', '_token']);
$connector = $this->model->findOrFail($id);
$connector->update($input);
return redirect()->action('UserController#show', [$id]);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$currentID = Auth::user();
$user = $this->model->findOrFail($id);
if ($currentID->id != $user->id) {
$user->delete();
} else {
Session::flash('flash_message', "You cant delete your own account!");
Session::flash('flash_type', 'alert-danger');
}
return redirect()->action('UserController#index');
}
And another example with a custom route:
Route::any('/datafeed/{id}/execute', 'DataFeedController#execute');
public function execute($id, $test = false) {
$results = $this->executeQuery($id, $test);
return view('datafeed.execute')->with('results', $results);
}
I'm not entirely sure on your plans (or even if you've fully read the documentation?) but you can access these functions by doing something similar to the following in your routes.php or Routes\web.php (depending on your version) file:
Route::get('/blog/create', 'BlogPostController#create');
Route::get('/blog/article/{id}', 'BlogPostController#show');
The first part is defining the route and the second part is saying what method should be run on the defined controller when this route is matched in the address bar. It doesn't always have to be get requests though, you can do get, post, patch and put

Categories