Routing when using api controller - laravel

i am really frustrated and dont know why i cannot route to my specified page like
profile
i am using an api controller and this is my controller and i am trying just to return a view
public function profile()
{
return view('layouts.main');
}
as simple as thats it just to return a view , all it does is that it reloads my welcome page
please i need your assistance
here is my api controller
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::apiResources(['user' => 'API\UserController']);
Route::get('profile', 'API\UserController#profile')->name('profile');
Route::put('profile', 'API\UserController#updateProfile');
Route::get('findUser', 'API\UserController#search');
Route::apiResources(['service' => 'API\ServiceController']);

If you put this in your api.php
for laravel 8
Route::resource("/users",UserController::class);
Than the routes will be automatically prefixed with /api. So the routes will look like this:
/api/users
/api/users/{user}
...
So you just have to suppose that the api prefix, is automatically added from routes/api.php.
but if you put it in your web.php
Route::resource("/users",UserController::class);
the routes will look like this:
{{ route('users.index') }}
{{ route('users.profile') }}
...
for create an action like profile you have to make that:
Route::resourse('profile',[UserController::class,'profile')->name('profile');
For more information about your routes, you can run php artisan route:list and you can check how do your routes look like.

Related

Laravel edit route for basic CRUD application giving 404

I'm trying to set up a basic Laravel 9 CRUD application, and I cannot get the edit route working for the User Controller.
routes/web.php
Route::get('/dashboard', function () { return view('dashboard'); })
->middleware(['auth'])->name('dashboard');
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{$id}/edit','edit')->middleware('auth');
Route::post('user/{$id}/edit','update')->middleware('auth');
Route::get('user/{$id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
require __DIR__.'/auth.php';
UserController.php
class UserController extends Controller
{
function edit(int $id)
{
echo 123;
}
I'm getting a 404 NOT FOUND page
Also, why don't I see the stack trace for this error?
Also, in some examples, I've seen people using the model class name as the parameter type in the controller method declaration, such as:
function edit(User $id)
{
echo 123;
}
However, I've also seen other examples using int instead. So which is the correct one?
First, inside your .env filte you should put
APP_ENV=local
APP_DEBUG=true
and change your web.php to:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth'])->name('dashboard');
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{id}/edit','edit')->middleware('auth');
Route::post('user/{id}/edit','update')->middleware('auth');
Route::get('user/{id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
require __DIR__.'/auth.php';
Then, try to run
php artisan route:list
and check if your routes are correct.
And try to remove middlewares inside user files, maybe you do not have login page and it redirects you there.
Be sure you are in the correct url like localhost/user/1/edit
Parameters in routes don't take a starting $. Change all occurrences of {$id} in your routes to just {id}:
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{id}/edit','edit')->middleware('auth');
Route::post('user/{id}/edit','update')->middleware('auth');
Route::get('user/{id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
More on Route Parameters
Edit: you might also want to take a look at Resource Controllers. Something like Route::resource('users', UserController::class); will manage all of the required routes

How to Set API routes in Laravel 8.0?

I was working in laravel 8.x, I have developed API to register, but when i test using postman also in browser the url [1]: http://127.0.0.1:8000/api/register always returns 404 not found message.
below is my api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['prefix' => 'v1'], function () {
Route::post('/login', 'UsersController#login');
Route::post('/register', 'UsersController#register');
Route::get('/logout', 'UsersController#logout')->middleware('auth:api');
});
can you please help?
Since you already put a route group "v1", all your routes must have that prefix, so just api/register wont work because that route doesn't exist inside your api.php, so infront of your routes just use
http://127.0.0.1:8000/api/v1/register
http://127.0.0.1:8000/api/v1/login
http://127.0.0.1:8000/api/v1/logout
Your routes looking fine.
I think you are forgetting to add http://127.0.0.1:8000/api/**v1**/register so please try with it once.

Laravel route not calling function of controller

I have a form in a page (blade) which redirects to a route which is to call a function in a controller however it does not even go inside the function because even a simple dd(); cannot be executed. when in route, if I change to
Route::post('edit/profile', function(Request $request){
dd($request);
});
it works. I tried to change both route's function name and controller's function name to another name still doesn't recognize.
My current route
Route::post('edit/profile', 'Auth\LoginController#updateUser');
My form line
<form action="{{url('/edit/profile')}}" method="post">
{{ csrf_field() }}
My function inside LoginController
public function updateUser(Request $request)
{
//insert code here
}
I know it's late, but did you solve the problem? I've had a simmilar issue, inside auth group a route was not working. In my case, I had to put the route after the "Route::resource". So make sure if your are making a route that has a resource tagged, add the other routes before the Route::resource. For example:
Route::group(['middleware' => ['auth']], function() {
Route::resource('category', 'CategoryController');
Route::get('category/order', 'CategoryController#order')->name('categoryOrder');
});
This won't work. Just put the 'category/order' route before the resource route like this:
Route::group(['middleware' => ['auth']], function() {
Route::get('category/order', 'CategoryController#order')->name('categoryOrder');
Route::resource('category', 'CategoryController');
});
This should work. Hope this helps someone.

Laravel using user id in route

So I have a route profile/{user_id}
How do I redirect user to that URL when they click on link?
Here's my controller:
{
function checkid($user_id) {
if (Auth::check())
{
$user_id = Auth::id();
return view('profile', [
'id' => $user_id
]);
}
}
}
Bit confused with the question but Laravel uses ID as default for dependency injection and changing it is easy: just change the routeKey in the model BUT in your instance, you're using the signed in user. So forgot the id!
<?php
namespace App\Http\Controllers;
class RandomController extends Controller {
public function index()
{
return view('profile');//use auth facade in blade.
}
}
In your routes use a middleware to prevent none authenticated users from reaching this method
<?php
Route::group('/loggedin', [
'middleware' => 'auth',
], function() {
Route::get('/profile', 'RandomController#index')->name('profile.index');
});
Now to redirect in your blade file use the route function, don't forget to clear your cache if you've cached your routes!
<h1>Hi! {{Auth::user()->name}}</h1>
View profile
Because I used the name method on the Route I can pass that route name into the route function. Using php artisan route:list will list all your route parameters which is cool because it will also tell you the names and middlewares etc.
if I had a route which required a parameter; the route function accepts an array of params as the second parameter. route('profile.index', ['I_am_a_fake_param' => $user->id,]).
Let me know if you need help with anything else.
You can redirect with the redirect() helper method like this:
return redirect()->url('/profile/' . $user_id);
But I'm not really following your usecase? Why do you want to redirect? Do you always want the user to go to their own profile? Because right now you are using the id from the authenticated user, so the user_id parameter is pretty much useless.

Laravel default Auth::routes() inside of group prefix

I'm attempting to create a prefix with a variable for "companies" to login to the platform. All users are tied to a company so the normal /login isn't desired. I'd like to use something like `/acme-company-name/login
I am using the default Laravel auth via: php artisan make:auth on a fresh install.
Route::group(['prefix' => '{company}'], function () {
Auth::routes();
});
When I try navigating to /company-name/login I see the following error:
Missing required parameters for [Route: login] [URI: {company}/login].
Looking inside the auto-generated login.blade.php I see the function call route('login') and this seems to be where everything is breaking. I think I need some way to supply a variable to that function or redefine what the "login" route is in some fashion ? I'd rather not have to replace the call Auth::routes() but will certainly do so if that is required to fix this issue.
I should note, i've tried defining the group 'as' => 'company' and changing route('company.login') but then I am told the route company.login is not defined.
Can you try by passing $company variable to the function as well?
Route::group(['prefix' => '{company}'], function ($company) {
Auth::routes();
});
And make sure you pass the company-name when calling the route as it's a required parameter.
In login.blade.php use {{ url("$company/login") }} instead of route('login').
route() helper has more than one parameter ;)
route('login', ['company' => $company])
you need to share your prefix in your views and set route as the following:
Route::group(['prefix' => '{company}'], function ($company) {
view()->share('company', $company); // share $company in views
Auth::routes();
});
now you have $company which is instance of Router and you need access to route prefix value for this you need get current route and get company parameter so you should rewrite your route() helper function as the following:
{{ route('login',['company'=>$company->getCurrentRoute()->__get('company')]) }}
// getCurrentRoute Get the currently dispatched route instance
//__get Dynamically access route parameters
EDIT:
you can write custom helper function as the following:
/**
* Generate the URL to a named route for Company Auth.
*
* #param string $name
* #param Router $company
* #return string
*/
function companyRoute($name,$company)
{
return app('url')->route($name, ['company'=>$company->getCurrentRoute()->__get('company')] ,true);
}
Please check the code that is working fine for me.
Route::group(['prefix' => '/{company}'], function () {
// ensure that auth controllers exists in right place (here it is App\Http\Controllers\Auth\LoginController)
// in LoginController funtion
Auth::routes();
//or you can try using custom routing like this
Route::get('{something}', function($company, $something)
{
var_dump($company, $something);
});
});
If you define this route at the end of the file then the error that you have mentioned we face.
ErrorException in UrlGenerationException.php line 17:
Missing required parameters for [Route: login] [URI: {company}/login]. (View: \resources\views\auth\login.blade.php)
Try with defining this route as first route in web.php and check.
Thanks
Looking inside the auto-generated login.blade.php I see the function call route('login') and this seems to be where everything is breaking.
Yes. By doing
Route::group(['prefix' => '{company}'], function () {
Auth::routes();
});
you are making all auth routes take a company parameter. So, in your views, instead of route('login'), you can do route('login', ['company' => Request::route('company')]). (And the same for all auth routes).
Then probably in your App\Http\Controllers\Auth\LoginController you will need to override the login method accordingly:
public function login(Request $request, $company)
{
// you can copy some behaviour from
// https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php#L28
}

Resources