Laravel not navigating to url based on database id - php

I am attempting to navigate to a product page with laravel. The URL gets an id which is obtained from the database id which it uses to display the product.
Products controller file:
public function index()
{
$products = Product::all();
return view('products.index')->with('products',$products);
}
public function show($id)
{
$product = Product::find($id);
return view('products.show')->with('product',$product);
}
Error:
The requested URL /products/1 was not found on this server.
Here's my routes as requested:
<?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('HomePage');
});
Route::get('/about', function () {
return view('pages.about');
});
/*
* Login
*/
Route::get('/login', [
'as' => 'login',
'uses' => 'UserLoginController#showLogin',
]);
Route::post('/login', 'UserLoginController#postLogin');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('products','productcontroller');

You don't have any route like this /products/1 so need to add that route and assign the controller and action that you need . Eg.
Route::get('/product/{id}', 'ProductController#show')

Edit: is your controller class named correctly? I think issue is there. Yes you can use resource route for restful request response but route can't find your controller class. Name it correctly. ProductsController or something. Double check.
Can you paste your route? Problem is probably there. Not in your controller. Check the documentation, if you can't figure it out paste here.

the href tag was wrong and needed to be exactly what was in the localhost e.g. localhost/8888/public

Related

Laravel keeps saying "Target class [NewsletterController] does not exist.", I've tried other stuff online, but nothing helped

I know there is a heck ton of links out there about Laravel not finding some class and stuff, but I really tried everything here and nothing works. I donĀ“t even know which code I should share here to help, so...I'll share my Newsletter controller and the web.php code
I'm using laravel 9.9 and php 8.1
web.php
<?php
Route::get('newsletter', 'App\Http\Controllers\NewsletterController#register');
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\NewsLetterController;
/*
|--------------------------------------------------------------------------
| 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('newsletter','NewsletterController#create');
Route::post('newsletter','NewsletterController#store');
Newsletter controler
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Newsletter;
class NewsLetterController extends Controller
{
public function create()
{
return view('newsletter');
}
public function store(Request $request)
{
if ( ! Newsletter::isSubscribed($request->email) )
{
Newsletter::subscribePending($request->email);
return redirect('newsletter')->with('success', 'Thanks For Subscribe');
}
return redirect('newsletter')->with('failure', 'Sorry! You have already subscribed ');
}
}
The issue is that your class name has a capital L for Letter, while on the route it does not, so your web.php should look like this:
<?php
Route::get('newsletter', 'App\Http\Controllers\NewsLetterController#register');
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\NewsLetterController;
/*
|--------------------------------------------------------------------------
| 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('newsletter','NewsLetterController#create');
Route::post('newsletter','NewsLetterController#store');
Maybe I am not sure
I think you can't use this method to write route in laravel 9 ...because I am using larvel 8 and it is not working so better to use:
Route::get('/usernewsletter, [NewsLetterController::class, 'create']);
https://laravel.com/docs/9.x/routing

using Laravel 7 Api routes

I'm trying to use simple laravel api for getting and sending requests, after define this api routes in api.php:
Route::prefix('Api/v1')->group(function () {
Route::any('login', 'Api\v1\AuthController#login');
Route::any('register', 'Api\v1\AuthController#register');
});
and creating AuthController in app/http/controller/Api/v1 directory:
class AuthController extends Controller
{
public function login()
{
dd(request()->all());
}
public function register()
{
dd(request()->all());
}
}
i get 404 error on this link:
http://127.0.0.1:8000/Api/v1/login
how can i resolve this problem?
Routes in api.php are automatically prefixed with /api. Currently, your routes are:
http://127.0.0.1:8000/api/Api/v1/login
http://127.0.0.1:8000/api/Api/v1/register
So navigating to http://127.0.0.1:8000/Api/v1/login is a 404.
If you remove /Api, and just use Route::prefix('/v1') ... then you should have no issue.
Also, always double check your routes with php artisan route:list to see what's wrong.
The API Routes are already prefixed by /api . I think the correct structure you'd looking for would be
Route::prefix('v1')->group(function () {
Route::any('login', 'AuthController#login');
Route::any('register', 'AuthController#register');
});
This way, you're calling the methods Login and Register from you /Controllers/AuthController file with the route
http://127.0.0.1:8000/api/v1/login
You can use many ways to define routes for API in laraval > routes > api.php file.
In this i'm going to explain how we can use routes group in the laraval..
Route::group([
'namespace' => 'Customers', //namespace App\Http\Controllers\Customers;
'middleware' => 'auth:api', // this is for check user is logged in or authenticated user
'prefix' => 'customers' // you can use custom prefix for your rote {{host}}/api/customers/
], function ($router) {
// add and delete customer groups
Route::get('/', [CustomerController::class, 'index']); // {{host}}/api/customers/ this is called to index method in CustomerController.php
Route::post('/create', [CustomerController::class, 'create']); // {{host}}/api/customers/create this is called to create method in CustomerController.php
Route::post('/show/{id}', [CustomerController::class, 'show']); // {{host}}/api/customers/show/10 this is called to show method in CustomerController.php parsing id to get single data
Route::post('/delete/{id}', [CustomerController::class, 'delete']); // {{host}}/api/customers/delete/10 this is called to delete method in CustomerController.php for delete single data
});
You can create controller using artisan command with default methods
php artisan make:controller Customers/CustomerController --resource

How to create multiple route with laravel 5.8

I'm using version 5.8 of laravel and I'm trying to initialize the routes. It is not possible to access the route created after the default route:
Route::get('/', function () {
return view('welcome');
});
I try to add a parameter in the second route:
Route::get('/page', ['as' => 'home', function (/page) {return view('page1') ;}]);
I got 404 error. How can I use multiple routes ?
This is my web.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('/page', function() { return view('page1'); })->name('home');
Route::get('/', function () {
return view('welcome');
});
Did you copied the second route, or what are you trying to do with this?
You can try this one instead as your syntax is wrong:
Route::get('/page', function() { return view('page1'); })->name('home');
-- EDIT
You can also return just the views from your routes if you don't plan to use a controller, like this:
Route::view('/', 'welcome');
Route::view('/page', 'page1');

Unable to prepare route [api/user] for serialization. Uses Closure

I'm writing my project on Laravel. When I optimize the project, I have a problem :
Unable to prepare route [api/user] for serialization. Uses Closure.
I looked for any closures in web.php, but I didn't find anything
<?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('/','ReviewsController#main')->name('main');
Route::post('/','MailController#verify')->name('verifyPost');
Route::get('/reviews', 'ReviewsController#index')->name('reviews');
Route::post('/reviews','ReviewsController#add')->name('addReview');
Auth::routes();
Route::group(['middleware' => 'admin','prefix' => 'admin'],function () {
Route::get('/', 'HomeController#index')->name('admin');
Route::get('/reviews', 'Admin\ReviewsController#get')->name('admin.reviews');
Route::get('/reviews/accepted/{id}','Admin\ReviewsController#accept')->where('id','\d+')->name('admin.accepted');
Route::delete('/reviews/delete','Admin\ReviewsController#delete')->name('reviews.delete');
});
in api.php file search and comment this route you will not get error..
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
and also in web.php file route::group is also closure and also comment them for test
Route::group(['middleware' => 'admin','prefix' => 'admin'],function () {
Route::get('/', 'HomeController#index')->name('admin');
Route::get('/reviews', 'Admin\ReviewsController#get')->name('admin.reviews');
Route::get('/reviews/accepted/{id}','Admin\ReviewsController#accept')->where('id','\d+')->name('admin.accepted');
Route::delete('/reviews/delete','Admin\ReviewsController#delete')->name('reviews.delete');
});
see what is closure
Php routing cache command :
php artisan route:cache
if your application using controller based routes. It help for fast execution. But remember "Closure based routes cannot be cached"
So kindly convert your Closure routes to controller classes.
For more information
Make sure to Check "routes/api.php"

Laravel Routes on Resource Controller. Using Show method with id = create instead of the create method

Below is my routes.php file in Laravel 5.1
When I access the /question/create url, the show method (meant for /question/{id} url) is called instead of the create method in the QuestionController.
I probably don't fully understand how the routes file interprets what I have below. Can someone help me understand how my file is being interpreted and why the show method is being called instead of the create method?
Note: This was working just fine when I did not have any route groups and middleware. Before I broke it, the routes file just had the resource controllers listed plain and simple (e.g. Route::resource('question','QuestionController'); )
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
//Home Route
Route::get('/','HomeController#getHome');
// Simple Static Routes (FAQ, PRIVACY POLICY, HONOR CODE, TERMS AND CONDITIONS ETC.). No Controller Required.
Route::get('faq',function(){
return view('legal/faq');
});
Route::get('privacypolicy',function(){
return view('legal/privacypolicy');
});
Route::get('honorcode',function(){
return view('legal/honorcode');
});
Route::get('termsandconditions',function(){
return view('legal/termsandconditions');
});
// Authentication routes (Middleware called by Controller)
Route::get('auth/login', 'Auth\AuthController#getLogin');
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
// Registration routes (Middleware called by Controller)
Route::get('auth/register', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
// Anyone can see the Home Page and Browse Questions, Courses and Universities
$routes = ['only' => ['index','show']];
Route::resource('question','QuestionController',$routes);
Route::resource('course','CourseController',$routes);
Route::resource('university','UniversityController',$routes);
// Routes Protected by Auth Middleware
Route::group(['middleware' => 'auth'],function(){
/*
* Students can view Solutions and Their Profiles
*/
Route::get('solution/{id}','QuestionController#postSolution');
Route::resource('user','UserController',['only' => ['show']]);
/*
* Only Editors have the ability to view the Create Questions Page,
* Store, Edit and Delete Questions that they created, that have not been solved yet
* Create, Edit and Delete Courses and Universities
*/
Route::group(['middleware' => 'editor'],function(){
$routes = ['only' => ['create','store','edit','update','destroy']];
Route::resource('question','QuestionController',$routes);
Route::resource('course','CourseController',$routes);
Route::resource('university','UniversityController',$routes);
/*
* Only Admins have the ability to delete resources
*/
Route::group(['middleware' => 'admin'],function(){
Route::get('admin/execute','AdminController#getExecute');
});
});
});
I see you have
$routes = ['only' => ['index','show']];
Route::resource('question','QuestionController',$routes);
Route::resource('course','CourseController',$routes);
Route::resource('university','UniversityController',$routes);
Before the group.
Right now because your route show is before the others like create It thinks create is a wildcard of show. So you should put the lines above at the bottom of the file.
Extra
I notice you have this in your group route
$routes = ['only' => ['create','store','edit','update','destroy']];
Its faster to write it as
$routes = ['except' => ['index','show']];
Except makes sure all routes are available except for the given routes.
And to see which routes are used you can enter the following in your terminal.
Php artisan route:list
Your resource controller has only 2 routes allowed based on your routes file : index and show.
$routes = ['only' => ['index','show']]; //
For example if this url home/create is server by a resource controller where you applied the above filter, the method show will be fired automatically. If you want the create method, just add it to your filter and run composer dump-autoload.

Categories