Getting error in Laravel 5.7 edit route page not found - laravel

Laravel Version 5.7
PHP 7+
I created a resource controller -> CategoryController [having all the magic methods]
This is the routes/web.php
Route::group(['as'=>'admin.','middleware'=>['auth','admin'],'prefix'=>'admin'], function(){
Route::get('/dashboard','AdminController#dashboard')->name('dashboard');
// product resource controller methods
// check php artisan r:l
Route::resource('product', 'ProductController');
Route::resource('category', 'CategoryController');
Route::resource('profile', 'ProfileController');
Route::post('remove', 'CategoryController#remove')->name('category.remove');
});
Now as you can see, I have "http://127.0.0.1:8000/admin/category/1/edit" for one of my categories to edit with category id = 1, that is also stored in the database.
<?php
namespace App\Http\Controllers;
use App\Category;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
public function index()
{
$categories = Category::paginate(3);
return view('admin.categories.index',compact('categories'));
}
public function edit(Category $category)
{
return "This is category edit page";
// dd($category);
// $categories = Category::where('id','!=', $category->id)->get();
// // dd($categories);
// return "This is category edit page";
// return view('admin.categories.create',['categories' => $categories, 'category'=>$category]);
}
When I try to go to this edit category page, it shows 404 page not found error.
Although, when I made an individual route for edit method with a closure function to return some text, it worked perfectly.
Route::get('category/{category}/edit', function($category){
return $category;
})->name('category.edit');

You didn't excluded full error you get, but try to change:
public function edit(Category $category)
{
return "This is category edit page";
}
into:
public function edit($category)
{
return "This is category edit page";
}
and see if it helps. If it helps, it means that there is no record matching id you passed or this record is soft deleted (or some additional conditions are not met) - Laravel uses Route model binding to match valid record.

try this
public function edit(Request $category)
{
return "This is category edit page";
}

Related

Attempt to read property "title" on null - Laravel

when I enter the detail page in Laravel, it gives an error. I don't understand where the error is coming from. My codes are as follows.
where is the problem? actually it says it's empty, but it needs to pull data from $blog on controller side.
Controller:
public function show($id)
{
$blog = Blog::where('id',$id)->first();
return view('front.detail',compact('blog'));
}
routes/web.php:
Route::prefix('{lang?}')->middleware('locale')->group(function() {
Route::get('/', [MainController::class, 'index'])->name('home');
Route::get('/about', [MainController::class, 'about'])->name('about');
Route::resource('/blogs', MainController::class)->only([ 'show']);
});
detail.blade.php:
<li>
<h2>{{$blog->title}}</h2>
<p>{!! $blog->text !!}</p>
</li>
If you want to get a model by the main column you use find not where and the column:
public function show($id)
{
$blog = Blog::find($id);
return view('front.detail',compact('blog'));
}
Then, find can return the Model (hence an object) or null, so in your case it is not finding the model by ID.
What you should use is findOrFail so it throws an exception if it did not find the model:
public function show($id)
{
$blog = Blog::findOrFail($id);
return view('front.detail',compact('blog'));
}
Then you can continue debugging why it is not found
Doesn't appear you are passing the blog ID in with your URL:
Route::resource('/blogs', MainController::class)->only([ 'show']);
Try changing your route to this:
Route::resource('/blogs/{id}', MainController::class)->only([ 'show']);
Your URL should be something like (where 5 is the blog ID):
http://yourdomain.com/blogs/5
You could also use binding:
// Route
Route::get('/blogs/{blog}', [MainController::class, 'show']);
public function show(Blog $blog)
{
return view('front.detail', ['blog' => $blog]);
}
More info can be found here:
Route model binding

How to architect a project which has more number of dynamic pages in laravel

I have a project which has a large number of dynamic pages. Approximately 30+ pages. The content of each page is different. what I did is created 30 tables and 30 routes as well. And on the admin side, there are 30+ modules to edit the contents. Is it the right way to do this?. In database table, different columns has to be kept.
// Route definition...
Route::get('/page1', [Page1Controller::class, 'show']);
Route::get('/page2', [Page2Controller::class, 'show']);
Route::get('/page3', [Page3Controller::class, 'show']);
// Controller method definition...
public function index() {
return view('page1');
}
// Route definition...
// All other routes above this slug catch all. otherwise it will try and hit this controller all the time and fail.
Route::get('/{slug}', [PageController::class, 'show']);
// Controller method definition...
public function show($slug)
{
$contents = PageContents::where('slug', $slug)->firstOrFail();
if ($contents) {
return view('page')->with('contents', $contents);
}
return view('404');
}
This way you have a table with all the contents you need. e.g. title, body copy so on. but if each layout is different you could also return a different view. e.g.
public function show($slug)
{
$contents = PageContents::where('slug', $slug)->firstOrFail();
if ($contents) {
return view('page-'.$slug)->with('contents', $contents);
}
return view('404');
}
You can create only one controller and add a parameter in the route(web.php):
web.php
//---Route Definition
Route::get('page/{page_number}', [PageController::class, 'show'])->name('page.show');
PageController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Crypt;
class PageController extends Controller {
//---Show
public function show($page_number) {
return view('show.show', compact('page_number'));
}//---End of Function show
}
If you want to retrieve your data from a database just one table is enough, just create a page table and give a field by the name of page_number and retrieve your specific page data by the given field.
For example:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Crypt;
class PageController extends Controller {
//---Show
public function show($page_number) {
$page = PageContent::where('page_number', $page_number)->first();
return view('show.show', compact('page'));
}//---End of Function show
}
**
Your Link to routes
<a href="{{ route('page.show', ['page_number' => 1])) }}" class="" title="Show">
Show
</a>

Get Current Category details in Laravel 5.6

I'm trying to fetch current category details.
For example, if the route is example.com/articles/category-slug
In my ArticleCategory Model
public function article(){
return $this->hasMany(Article::class);
}
In Article Model
public function category(){
return $this->belongsTo(ArticleCategory::class, 'category_id');
}
Routes
Route::group(['prefix' => 'articles'], function(){
Route::get('/', 'Frontend\ArticleController#index')->name('articles.index');
Route::get('/{articlecategory}', 'Frontend\ArticleController#category');
Route::get('/{articlecategory}/{slug}', 'Frontend\ArticleController#show');
});
ArticleController
public function category(Request $request, ArticleCategory $articlecategory)
{
$category = $articlecategory->id;
$currentcategory = ArticleCategory::where('id', $category)->first();
return $currentcategory;
}
i have created two categories, 1. Updates 2. News
When i go to the url example.com/articles/updates i receive a error "Page Not Found"
When i change the {{ articlecategory }} to {{ category }} only in the routes file. It shows a blank page without the current category details. How to solve this?
Note: I used the same code earlier in Laravel 5.5 and it worked well. In Laravel 5.6 i see this error. I'm already using a cache killer on chrome and have also cleared cache and views in laravel as suggested by few links on google. However i still see the same error
I found out a way that worked.
I have changed route key value to slug and it worked. I thought that was done by the slugs package i was using. After adding the below code manually to the models it works as expected.
public function getRouteKeyName()
{
return 'slug';
}
If you would like model binding to use a database column other than id when retrieving a given model class, you may override the ‍‍getRouteKeyName method on the Eloquent model:
for example :
class ArticleCategory extends Model
{
public $table='article_category';
public function article(){
return $this->hasMany(Article::class);
}
public function getRouteKeyName()
{
return 'category_slug';
}
}
and my article_category table :
| category_slug | name | id |
|:-------------:|:-------:|:--:|
| cat1 | Updates | 1 |
| cat2 | News | 2 |
your routes should be :
Route::group(['prefix' => 'articles'], function(){
Route::get('/', 'Frontend\ArticleController#index')->name('articles.index')->name('articles');
Route::get('/{category}', 'Frontend\ArticleController#category')->name('category');
Route::get('/{category}/{slug}', 'Frontend\ArticleController#show')->name('category_articals');
});
now you are passing a category_slug to your controller then
example: example.com/articles/news
in your controller :
public function category(Request $request,$category)
{
$category = ArticleCategory::where('slug',$category)->first();
if($category){
// category found , return category to page
return view('category',compact('category'));
}else{
// category not found , return 404 page
return view('error.404');
}
}

Table Bring all comments for one article using yajra/laravel-datatables

when try to get all comment for one Article by Article::first() but first()
Bring just the first article
i try use find() like
$comments = Article::find()-> commentsArticle()->with('articles');
return Datatables::of($comments)
i get error so how i can Pass a value to view all comments for one article
or
my be there is way without using find()
Article model
class Article extends Model{
public $table = 'articles';
public function commentsArticle() {
return $this->hasMany('App\Comment');
}
}
controller
enter code here
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use App\Article;
use App\Comment;
class CommentController extends Controller{
public function commentsForOne Article()
{
$comments = Article::all()->commentsArticle->with('articles');
return Datatables::of($comments)->make(true);
}
}
last error i get
ErrorException (E_DEPRECATED)
Non-static method Yajra\Datatables\Datatables::collection() should
not be called statically
I hope find any idea or example like that will help me to learn
You are trying to get the first articles with its comments.
public function commentsForOneArticle($id)
{
$article = Article::fine($id);
//check if article exists to avoid errors
if ( $article ) {
return Datatables::of(Comment::where('article_id', $article->id))->make(true);
}
return "no article with id" . $id;
}
This was just an illustration. But it seems you need to understand first how Eloquent works. Watch this free Laracast https://laracasts.com/series/laravel-from-scratch-2017/episodes/7
For routes, you can define the route like this:
Route::get('comments/{article_id}', 'ArticleController#commentsForOneArticle');
And call it in Ajax like
$.ajax({url: "/comments/1",
success: function(result){
//do stuff here
},
error: function(error) {
console.log(error)
}
});
All this is just a guide and not THE solution.
Edit
To take data with the user in one go
$article = Article::with('user')->find($id);
//will include all the fields from user and article
Comments & author
To get the name of the comment author, you need to define the relationship in comment model
public function user() {
return $this->belongsTo(User::class);
}
Then get like this
if ( $article ) {
return Datatables::of(Comment::with('users')->where('article_id', $article->id))->make(true);
}

The localhost page isn’t working in laravel

Here is my controller code:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Route;
use Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\models\Designation;
use Validator;
class Cdesigination extends Controller
{
public $flight;
public function __construct(){
$this->flight = new Designation;
}
public function index(request $request)
{
$this->flight->name = $request->name;
$this->flight->detail = $request->detail;
$this->flight->token_key = $request->_token;
$data=$this->flight->save();
if($data){
return Redirect::to('posts')->withInput()->with('success', 'Inserted Successfully.');
}
else {
return Redirect::to('posts')->withInput()->with('success', 'Not inserted Successfully.');
}
return view('designation');
}
}
Here is route code:
Route::get('/posts', 'Cdesigination#index');
Where is trouble and how to solve it?
I think redirect keyword create trouble because when i raze the redirect:: to keyword then working fine.
Its not the Redirect. You are using withInput() and with('success', 'Inserted Successfully.'). Use any one. You might want to erase withInput() and try. Also do you not get laravel errors displayed on your page ?
It seems you're going to /posts which uses Cdesigination#index action. And this action always redirects to the same page, to itself. And it will be redirected to itself again and again and again.
So view('designation') will never be loaded:
if ($data) {
// If $data is true, redirect
return Redirect::to('posts')->withInput()->with('success', 'Inserted Successfully.');
} else {
// If not, redirect too
return Redirect::to('posts')->withInput()->with('success', 'Not inserted Successfully.');
}
// Any code here will never be executed
I'm not sure what are you trying to accomplish, but if you want to load designation view with messages, you should do something like this:
if ($data) {
// If $data is true, redirect
return view('designation')->withInput()->with('success', 'Inserted Successfully.');
} else {
// If not, redirect too
return view('designation')->withInput()->with('success', 'Not inserted Successfully.');
}

Resources