I have a problem that I can not resolve in Laravel 5.4.
I'm using the Postman extension to make requests for my API, so far it works normally with GET, but when I try to do a POST, the method that's actually called is GET again. (The API can not have authentication or token for the user).
api.php:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['api' => ['auth:api']], function(){
Route::group(['prefix' => 'user'], function(){
Route::get('{id}', ['uses' => 'UserController#getUser']);
Route::post('', ['uses' => 'UserController#saveUser']);
Route::get('', ['uses' => 'UserController#allUsers']);
Route::put('{id}',['uses' => 'UserController#updateUser']);
Route::delete('{id}', ['uses' => 'UserController#deleteUser']);
});
});
UserController.php:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller{
protected $user = null;
public function __construct(User $user){
$this->user = $user;
}
public function allUsers(){
return $this->user->allUsers();
}
public function getUser($id){
}
public function saveUser(){
return $this->user->saveUser();
}
public function updateUser($id){
}
public function deleteUser($id){
}
}
User.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $hidden = ['venda','remember_token', 'created_at','updated_at'];
public $fillable = ['nome','email', 'venda'];
public function allUsers(){
return self::all();
}
public function saveUser(){
$input = Input::all();
echo 'aa';
$user = new User();
$user->fill($input);
$user->save();
return $user;
}
}
First change this:
Route::group(['api' => ['auth:api']], function(){
To:
Route::group(['middleware' => ['auth:api']], function(){
Related
i found a issue it say 'Class admin does not exist'. Anything I missing for the issue? Thanks.
Here is my Route.php
Route::group(['prefix' => 'admin', 'middleware'=> ['auth' => 'admin']], function () {
Route::get('/','AdminController#index');
Route::get('profile','AdminController#profile');
Route::get('/addProduct','AdminController#addProduct');
});
Here is my AdminController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdminController extends Controller
{
public function index(){
return view('admin.index');
}
public function profile(){
return view('admin.profile');
}
public function addProduct(){
return view('admin.addProduct');
}
}
Issue with in the route file to assign middlewares to route group
If you have two middlewares then assign like this ["auth", "admin"] instead of ["auth" => "admin"].
Route::group(['prefix' => 'admin', 'middleware'=> ['auth', 'admin']], function () {
Route::get('/','AdminController#index');
Route::get('profile','AdminController#profile');
Route::get('/addProduct','AdminController#addProduct');
});
While i was working on my laravel project i got this error and i am unable to solve it even after so much changes and effort. I hope i get some solution.
My ERROR:
Symfony\Component\Debug\Exception\FatalThrowableError thrown with
message "Class 'App/Post' not found"
CommentsController.php
<?php
namespace App\Http\Controllers;
use \Auth;
use App\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests;
use App\Comment;
use Session;
use DB;
class CommentsController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'comment' => 'required'
]);
$post = Post::find('id');
$comments = new Comment();
$comments->name = $request->name;
$comments->email = $request->email;
$comments->comment = $request->comment;
$comments->approved = true;
$comments->post()->associate($post);
$comments->save();
Session::flash('success', 'Comment was added');
return redirect()->route('posts.show', [$post->id]);
//return redirect('/posts')->with('success', 'Comment Created
Successfully');
}
}`
Post.php
`
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//Table Name
protected $table = 'posts';
//Primary Key
public $primaryKey = 'id';
//Timestamps
public $timestamps = true;
public function user(){
return $this->belongsTo('App\User');
}
public function comment(){
return $this->hasMany('App\Comment');
}
}
`
My Web.php (Route File)
`
Route::get('/', 'PagesController#index');
Route::get('/about', 'PagesController#about');
Route::get('/contact', 'PagesController#contact');
Route::get('/services', 'PagesController#services');
// Post Pages
Route::resource('posts', 'PostsController');
// Login Authorization
Auth::routes();
// Dashboard
Route::get('/dashboard', 'DashboardController#index');
// Comments
Route::post('/posts/{post_id}', ['uses'=>'CommentsController#store' , 'as' => 'comments.store']);
`
Write this code top of the controller....
use App\Post;
or
Change this code...
$post = Post::find('id');
To
$post = \App\Post::find('id');
I think this is solved.
pay attention about file Post.php
use App\Post;
just A is Capital not all APP
Web.php
Route::get('/' , ['as' => '/' , 'uses'=> 'loginController#getlogin']);
Route::post('/login', ['as' => 'login', 'uses'=> 'loginController#postlogin']);
Route::group(['middleware' =>['authen']],function (){
Route::get('/logout' ,['as'=>'logout', 'uses'=> 'loginController#getLogout']);
Route::get('/dashboard',['as'=>'dashboard', 'uses'=> 'dashboardController#dashboard']);
});
dashboardController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class dashboardController extends Controller
{
public function __construct()
{
$this->middleware('web');
}
public function dashboard()
{
return view('layouts.master');
}
}
Authen.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authen
{
public function handle($request, Closure $next ,$guard ='web')
{
if (!Auth::guard($guard)->check())
{
return redirect()->route('/');
}
return $next($request);
}
}
loginController
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;
class loginController extends Controller
{
use AuthenticatesUsers;
protected $username = 'username';
protected $redirectTo = '/dashboard';
protected $guard = 'web';
public function getLogin()
{
if (Auth::guard('web')->check())
{
return redirect()->route('dashboard');
}
return view('login');
}
public function postlogin(Request $request)
{
$auth = Auth::guard('web')->attempt(['username'=>$request->username,'password'=>$request->password,'active'=>1]);
if ($auth)
{
return redirect()->route('dashboard');
}
return redirect()->route('/');
}
public function getLogout()
{
Auth::guard('web')->logout();
return redirect()->route('/');
}
}
When I try to login it redirects to the same page i.e login page, I tried to solve this problem but I can't. I want to redirect dashboard through login page, but it is not happen. There is no error shown and I can't go on dashboard page too.
Try this way in postlogin function to check user authentication.
$auth = Auth::attempt(['username'=>$request->username,'password'=>$request->password,'active'=>1]);
if($auth){
//do something...
}
So i have a 'TicketController' which holds my functions for manipulating 'tickets' in a system.
I am looking to work out the best way to send my new route that will take a route parameter of {id} to my TicketController to view a ticket.
Here is my route set
Route::group(['middleware' => 'auth', 'prefix' => 'tickets'], function(){
Route::get('/', 'TicketController#userGetTicketsIndex');
Route::get('/new', function(){
return view('tickets.new');
});
Route::post('/new/post', 'TicketController#addNewTicket');
Route::get('/new/post', function(){
return view('tickets.new');
});
Route::get('/view/{id}', function($id){
// I would like to ideally call my TicketController here
});
});
Here is my ticket controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Ticket;
use App\User;
class TicketController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Returns active tickets for the currently logged in user
* #return \Illuminate\Http\Response
*/
public function userGetTicketsIndex()
{
$currentuser = \Auth::id();
$tickets = Ticket::where('user_id', $currentuser)
->orderBy('updated_at', 'desc')
->paginate(10);
return view('tickets.index')->with('tickets', $tickets);
}
public function userGetTicketActiveAmount()
{
$currentuser = \Auth::id();
}
public function addNewTicket(Request $request)
{
$this->validate($request,[
'Subject' => 'required|max:255',
'Message' => 'required|max:1000',
]);
$currentuser = \Auth::id();
$ticket = new Ticket;
$ticket->user_id = $currentuser;
$ticket->subject = $request->Subject;
$ticket->comment = $request->Message;
$ticket->status = '1';
$ticket->save();
}
public function viewTicketDetails()
{
//retrieve ticket details here
{
}
You don't need to use closure here. Just call an action:
Route::get('/view/{id}', 'TicketController#showTicket');
And in TicketController you'll get ID:
public function showTicket($id)
{
dd($id);
}
More about this here.
You should use type-hint in laravel. Its awesome
In route
Route::get('/view/{ticket}', 'TicketController#viewTicketDetails');
In controller
public function viewTicketDetails(Ticket $ticket)
{
//$ticket is instance of Ticket Model with given ID
//And you don't need to $ticket = Ticket::find($id) anymore
{
I use Laravel 5.2 and have a problem with middleware.
There is the code in the routes.php
use Illuminate\Contracts\Auth\Access\Gate;
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', 'HomeController#index');
});
Route::group(['prefix'=>'admin', 'middleware' => 'admin'], function(){
Route::get('/', function(){
return view('admin.index');
});
Route::get('/user', function(){
return view('admin.user');
});
});
Kernel.php:
protected $routeMiddleware = [
...
'admin' => \App\Http\Middleware\AdminPanel::class,
];
AdminPanel.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use App\Role;
class AdminPanel
{
public function handle($request, Closure $next)
{
$user = Auth::user();
dd($user);
if($user){
$role = Role::whereName('admin')->first();
if($user->hasRole($role)){
return $next($request);
}
}
return redirect('/');
}
So, $user = Auth::user() always return null.
Thanks for suggestions!
I faced a situation where Auth::user() always returns null, it was because I was trying to get the User in a controller's constructor.
I realized that you can't access the authenticated user in your controller's constructor because the middleware has not run yet.
As an alternative, you can define a Closure based middleware directly in your controller's constructor.
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
class ProjectController extends Controller
{
protected $user;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
}
Any route that uses Auth() must be encapsulated in the web middleware. You're close, just move your Route::group(['prefix' => 'admin'], ...) into the group above.
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', 'HomeController#index');
// Moving here will ensure that sessions, csrf, etc. is included in all these routes
Route::group(['prefix'=>'admin', 'middleware' => 'admin'], function(){
Route::get('/', function(){
return view('admin.index');
});
Route::get('/user', function(){
return view('admin.user');
});
});
});
Define middleware in the constructer of your controller and it will do the trick here
public function __construct()
{
$this->middleware('auth:api');
}
I had the same problem because i did not set the table name.
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'users';
I found a solution in an old code
function getAuth($guard, $get)
{
return auth($guard)->user()->$get;
}
add this ^ as a helper function and use it wherever you want
ex:
getAuth('user', 'id');
just include your authentication middleware in call
$user = auth('middleware')->user()
Route::middleware('auth:api')->group(function () {
Route::get('/details', 'UserController#details');
});
My Auth::user() return null in view when
I don't have users table in database
I don't have id field as primary key of table users