Laravel routing issues - php

I'm trying to make a get request to rest api, route bellow:
Route::group(
['middleware' => 'api'],
function() {
Route::get('users', 'UserApiController#index')->name('api.user.list');
Route::get('users/{user}', 'UserApiController#show')->name('api.user.user');
Route::post('users', 'UserApiController#store')->name('api.user.create');
Route::put('users/{user}', 'UserApiController#update')->name('api.user.update');
Route::delete('users/{user}', 'UserApiController#destroy')->name('api.user.delete');
Route::patch('users/{user}/credentials', 'UserApiController#setCredentials')->name('api.user.set_credentials');
Route::get('users/credentials', 'UserApiController#findByCredentials')->name('api.user.find_by.credentials');
Route::get('users/email/{email}', 'UserApiController#findByEmail')->name('api.user.find_by.email');
Route::get('users/phone/{phone}','UserApiController#findByPhone')->name('api.user.find_by.phone');
});
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests\CreateUserRequest;
use App\Http\Requests\SetCredentialsRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Models\User;
use App\Models\UserEmail;
use App\Models\UserPhone;
use Illuminate\Http\JsonResponse;
use App\Http\Resources\User as UserResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class UserApiController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(): JsonResponse
{
return response()->json(
['data' => UserResource::collection(User::all())],
200
);
}
/**
* Display the specified resource.
*
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function show(User $user): JsonResponse
{
return response()->json(
['data' => new UserResource($user)],
200
);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(CreateUserRequest $request): JsonResponse
{
try {
DB::beginTransaction();
$user = (new User())
->create(
$request->only(['uuid', 'first_name', 'last_name'])
);
$email = $request->get('email');
$user->emails()->save(
new UserEmail(['email' => $email])
);
DB::commit();
} catch (\Throwable $exception) {
DB::rollBack();
return response()
->json(['error' => $exception->getMessage()], 500);
}
return response()->json(
['data' => new UserResource($user)],
201
);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function update(UpdateUserRequest $request, User $user): JsonResponse
{
$user->update($request->only(['username', 'password', 'first_name', 'last_name']));
return response()->json(
['data' => new UserResource($user)],
200
);
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function destroy(User $user): JsonResponse
{
$user->delete();
return response()->json(
null,
204
);
}
public function setCredentials(SetCredentialsRequest $request, User $user)
{
$user->update([
'username' => $request->get('username'),
'password' => \password_hash($request->get('password'), \PASSWORD_BCRYPT),
]);
return response()->json(
['data' => new UserResource($user)],
200
);
}
public function findByCredentials(Request $request)
{
}
public function findByEmail(string $email)
{
$user = UserEmail::all()
->where('email', '=', $email)
->first()
->user()
->getResults();
return response()->json(
['data' => new UserResource($user)],
200
);
}
public function findByPhone(string $phone)
{
$user = UserPhone::all()
->where('phone', '=', $phone)
->first()
->user()
->getResults();
return response()->json(
['data' => new UserResource($user)],
200
);
}
}
Got an error:
No query results for model [App\\Models\\User] credentials
As I understand,laravel is attempting to find credentials field in User model to resolve it.
Controller method is never handled.
If I use Route::post - everything is ok.
How to disable "auto-finding", so I could get control in the controller?

Changing the possion of the route solved the problem:
Route::group(
['middleware' => 'api'],
function() {
Route::get('users/credentials', 'UserApiController#findByCredentials')->name('api.user.find_by.credentials');
Route::get('users', 'UserApiController#index')->name('api.user.list');
Route::get('users/{user}', 'UserApiController#show')->name('api.user.user');
Route::post('users', 'UserApiController#store')->name('api.user.create');
Route::put('users/{user}', 'UserApiController#update')->name('api.user.update');
Route::delete('users/{user}', 'UserApiController#destroy')->name('api.user.delete');
Route::patch('users/{user}/credentials', 'UserApiController#setCredentials')->name('api.user.set_credentials');
Route::get('users/email/{email}', 'UserApiController#findByEmail')->name('api.user.find_by.email');
Route::get('users/phone/{phone}','UserApiController#findByPhone')->name('api.user.find_by.phone');
});

Related

For some routes I get "The payload is invalid" in laravel

I have the following routes in web.php, the first five routes are working perfectly but from contacts to aboutroutes` fail with the following exception:
Illuminate\Contracts\Encryption\DecryptException The payload is invalid.
Route::get('services', 'PageController#services')->name('services');
Route::get('/service/{id}', 'PageController#showService')->name('service');
Route::get('/blogs', 'PageController#showBlogs')->name('blogs');
Route::get('/{blog}', 'PageController#showPost')->name('post.show');
Route::post('/comment/{blog}/store', 'PageController#storeComment')->name('comment.store');
Route::get('/contacts', 'PageController#contacts')->name('contacts');
Route::post('/contact/store', 'PageController#storeContact')->name('contact.store');
Route::get('/courses', 'PageController#showCourses')->name('courses');
Route::get('/{course}', 'PageController#categoryCourses')->name('course.category');
Route::get('coursesdetail', 'PageController#showCoursesDetail')->name('coursesdetail');
Route::get('resource', 'PageController#showResource')->name('resource');
Route::get('about', 'PageController#showAbout')->name('about');
PageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use App\About;
use App\Team;
use App\Service;
use App\Post;
use App\Category;
use App\Tag;
use App\Slider;
use App\Contact;
use App\Client;
use App\Comment;
use App\Course;
use App\Coursecategory;
class PageController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$about = About::all();
$teams = Team::all();
$services = Service::all();
$posts = Post::orderBy('created_at', 'desc')->take(3)->get();
$sliders = Slider::all();
$clients = Client::all();
return view('index')->with('about', $about)
->with('teams', $teams)
->with('services', $services)
->with('posts', $posts)
->with('sliders', $sliders)
->with('clients', $clients);
}
/**
* 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)
{
//
}
public function services()
{
$services = Service::all();
return view('service')->with('services', $services);
}
public function showService($id)
{
$id = Crypt::decrypt($id);
$service = Service::find($id);
$services = Service::all();
return view('service')->with('service', $service)->with('services', $services);
}
public function showBlogs()
{
// $posts = Post::orderBy('created_at', 'desc')->take(5)->get();
// $recents = Post::orderBy('created_at', 'desc')->take(5)->get();
$posts = Post::orderBy('created_at', 'desc')->paginate(4);
$recents = Post::orderBy('created_at', 'desc')->take(4)->get();
// $posts = Post::all();
$tags = Tag::all();
$categories = Category::all();
return view('blogs')->with('tags', $tags)
->with('categories', $categories)
->with('posts', $posts)
->with('recents', $recents);
}
public function showPost(Request $request, $id)
{
$id = Crypt::decrypt($id);
$posts = [Post::find($id)];
$recents = Post::orderBy('created_at', 'desc')->take(4)->get();
$tags = Tag::all();
$categories = Category::all();
// $next_id = Post::where('id', '>', $id)->min('id');
// $prev_id = Post::where('id', '<', $id)->max('id');
// dd($posts);
return view('post')->with('posts', $posts)
->with('recents', $recents)
->with('tags', $tags)
->with('categories', $categories);
// ->with('next', Post::find($next_id))
// ->with('prev', Post::find($prev_id));
}
public function storeComment(Request $request, $post)
{
request()->validate([
'name' => 'required',
'email' => 'required|email',
'phone' => 'required',
]);
$contact = Comment::create([
'post_id' => $post,
'user_id' => Auth::id(),
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'comment' => $request->comments,
]);
session()->flash('success', 'Comment successfully submitted');
return redirect()->back();
}
public function contacts()
{
return view('contact');
}
public function storeContact(Request $request)
{
request()->validate([
'name' => 'required',
'email' => 'required|email',
'phone' => 'required',
]);
$contact = Contact::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'comment' => $request->comments,
]);
session()->flash('success', 'Contact information successfully submitted');
return redirect()->route('contact');
}
public function showCourses()
{
$categories = Coursecategory::all();
$courses = Course::orderBy('created_at', 'desc')->paginate(4);
return view('courses')->with('courses', $courses)
->with('categories', $categories);
}
public function categoryCourses($id)
{
$id = Crypt::decrypt($id);
$course = Coursecategory::where('id', $id)->first()->courses;
$categories = Coursecategory::all();
return view('coursewithcategory')->with('course', $course)
->with('categories', $categories);
}
public function showCoursesDetail()
{
return view('coursesdetail');
}
public function showResource()
{
return view('resource');
}
public function showAbout()
{
$about = About::all();
return view('about')->with('about', $about);
}
}
This should be the order your routes when you use uri as slug.
Route::get('/contacts', 'PageController#contacts')->name('contacts');
Route::post('/contact/store', 'PageController#storeContact')->name('contact.store');
Route::get('/courses', 'PageController#showCourses')->name('courses');
Route::get('coursesdetail', 'PageController#showCoursesDetail')->name('coursesdetail');
Route::get('resource', 'PageController#showResource')->name('resource');
Route::get('about', 'PageController#showAbout')->name('about');
Route::get('/{course}', 'PageController#categoryCourses')->name('course.category');

"Type error: Too few arguments to function App\Http\Controllers\UserController::create(), 0 passed and exactly 1 expected"

I have a problem with inserting Data into Database. Let's say I have a controller named HeroController and I want to create a new hero object and insert it to my database as a new hero.
My controller contains the following method:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// return response()->json([
// 'name' => 'Abigail',
// 'state' => 'CA'
// ]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6',
]);
}
public function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data[password]),
]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$user = $request->isMethod('put');
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
return response()->json($usere, 201);
}
/**
* 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)
{
//
}
}
My routes.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('/', function () {
return view('welcome');
});
Route::get('/users/create', 'UserController#create');
This is the error that i got. Type error: Too few arguments to function App\Http\Controllers\UserController::attendance(), 0 passed and exactly 1 expected". I am new to laravel.
You are using a get request to call create function.
Route::get('/users/create', 'UserController#create');
So, you are not passing any data to that controller. Hence the error.
First, you'll want to change the visibility of create and validator:
protected function create(array $data)
And the validator method:
protected function validator(array $data)
Then you'll want to change your /users/create route to a post and to use the store method:
Route::post('/users/create', 'UserController#store');
In your UserController update your store method to:
public function store(Request $request)
{
// validate the request
$validator = $this->validator($request->all());
if ($validator->fails()) {
return response()
->json(422,$validator->errors()->messages());
}
$user = $this->create($request->all());
return response()->json($user, 201);
}
If you need some sort of form to register or create a user, add an additional method in your controller:
public function register()
{
return view('user.register');
}
Then define another get route:
Route::get('/users/register', 'UserController#register');
Route::delete('/file/{id}','FileController#destroy')->name('deletefile');
Hope it will be helpful

Using named routes in protected methods in Laravel Controller

In my LoginController I have:
protected $redirectTo = '';
I then do this:
public function boot()
{
Parent::boot();
$this->redirectTo = route('org.home');
$this->logoutTo = route('user.login');
}
But in a method in the controller I check and I get a BLANK value from $this->redirectTo
protected function authenticated(Request $request, $user)
{
dd($this->redirectTo);
}
How do I make the value of this variable dynamic and use the route name to assign its value?
Here is my whole controller based on the comments below:
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Which Authentication Guard we are working with
*
* #var string
*/
protected $guard = 'user';
/**
* URI where we redirect to after registration
*
* #var string
*/
protected $redirectTo = '';
/**
* URI where we redirect to after logout
*
* #var string
*/
protected $logoutTo = '';
/**
* LoginController constructor.
*/
public function __construct()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Parent::boot();
$this->redirectTo = route('org.home');
$this->logoutTo = route('user.login');
}
/**
* Show the application's login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('auth.user.main.login');
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
Auth::guard($this->guard)->logout();
$request->session()->flush();
$request->session()->regenerate();
if ($request->ajax()) {
return response()->json([
'type' => 'success',
'message' => trans('auth.logout_ok')
]);
} else {
return redirect($this->logoutTo ?: '/');
}
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
// If this user belongs to a partner
if ($user->isPartner()) {
// And the partner is active, then continue
if (!$user->partner->isActive()) {
// Else respond with an error
$error = [
'type' => 'error',
'message' => trans('messages.partner_inactive')
];
if ($request->ajax()) {
return response()->json($error);
} else {
return redirect()->back()->withErrors($error);
}
}
}
dd($this->redirectTo);
// Set up the user's session
$this->setupSession();
if ($request->ajax()) {
return response()->json([
'type' => 'success',
'user' => auth()->check(),
'intended' => $this->redirectPath(),
'message' => trans('auth.logout_ok')
]);
} else {
return redirect()->intended($this->redirectPath());
}
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
if ($this->authenticated($request, $this->guard()->user())) {
return true;
} else {
if ($request->ajax()) {
return response()->json([
'type' => 'error',
'user' => auth()->check(),
'intended' => $this->redirectPath(),
'message' => trans('auth.not_login')
]);
} else {
return redirect()->intended($this->redirectPath());
}
}
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
/**
* Set up all session variables here
*/
private function setupSession()
{
// session()->put('user', Auth::user());
}
}
I had to put my assignments here
public function __construct()
{
$this->redirectTo = route('org.home');
$this->logoutTo = route('user.login');
}

Laravel Roles without pivot table

I am student and i am new with Laravel and i have this UserController which used to assign multi Roles to User (using pivot table user_role) but i want to assign one role to each user (without pivot table) so i added role_id foreign in table user but i dont know what to change in UserController file.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Role;
use DB;
use Hash;
class UserController extends Controller
{
/**
* 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('display_name','id');
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);
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
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('display_name','id');
$userRole = $user->roles->pluck('id','id')->toArray();
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('role_user')->where('user_id',$id)->delete();
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
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');
}
}
and you can find all the code here:
http://itsolutionstuff.com/post/laravel-52-user-acl-roles-and-permissions-with-middleware-using-entrust-from-scratch-tutorialexample.html
this mean so much to me if you help me and thanks.

Method [all] does not exist in Laravel 5.2

just now I get this issues that is bothering me.
the error in code after validator::make in update function.
BadMethodCallException in Controller.php line 107: Method [all] does
not exist.
This is the full code from BooksController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\book;
class BooksController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$book = BooksController::all();
return view('book.index')->with('book', $book);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return view('book.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'judul' => 'required',
'author' => 'required',
'penerbit' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('book/create')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$book = new book;
$book ->judul = Input::get('judul');
$book ->author = Input::get('author');
$book ->penerbit = Input::get('penerbit');
$book ->save();
// redirect
Session:flash('message', 'Berhasil membuat buku!');
return Redirect::to('book');
}
}
/**
* Display the specified resource.
*
* #param int $idate
* #return Response
*/
public function show($id)
{
$book = books::find($id);
return view('book.show')
->with('book', $book);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$book = books::find($id);
return view('book.edit')
->with('book', $book);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
$rules = array(
'judul' => 'required',
'author' => 'required',
'penerbit' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('book/' . $id . '/edit')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// simpan
$book = books::find($id);
$book->judul = Input::get('judul');
$book->author = Input::get('author');
$book->penerbit = Input::get('penerbit');
$book->save();
// redirect
Session::flash('message', 'Berhasil mengganti info buku!');
return Redirect::to('book');
}
}
/**
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$book = books::find($id);
$book ->delete();
//redirect
Session::flash('message', 'Berhasil menghapus buku!');
return Redirect::to('book');
}
}
try this use Validator; instead of
use Illuminate\Support\Facades\Validator;
convert user Input::all() to input()->all() or request()->all()

Categories