Inputting to a Controllers closure in laravel 5.2 - php

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
{

Related

deleting a user with query builder laravel

I'm trying to delete a user account using laravel query builder so I'm doing this
AuthRepository
class AuthRepository implements IAuthRepository
{
....
public function delete($user_id)
{
$res = User::where('id', $user_id->id)->delete();;
if ($res) {
return response('Success, user was deleted', 204);
} else {
return response()->json(error);
}
}
}
In controller
class AuthController extends Controller
{
protected $auth;
public function delete($user_id)
{
return $user_id->delete();
}
}
in api.php
Route::group(['prefix' => 'auth'], function () {
Route::group(['middleware' => 'auth:api'], function () {
// Delete user
Route::post('user/delete/{user_id}', 'AuthController#delete');
});
});
Passing user_id to ${API_URL}/auth/user/delete/{user_id} I'm facing
Call to a member function delete() in Controller on line return $user_id->delete();. Can someone please explain me why is this happening, thanks.
Take advantage of the route model binding and to this instead:
public function delete(User $user)
{
return $user->delete();
}
And your route:
Route::post('user/delete/{user}', 'AuthController#delete');
You cannot call delete() on an integer.
If you don't want to use the Route model binding as suggested by #nakov and insist on using id then you have to get the user first before deleting.
public function delete($user_id)
{
$user = User::findOrFail($user_id);
return $user->delete();
}

How to update email value in laravel

We know that laravel has an update () method that updates records using the http "put" method. But I do not know how to create an edpoint in which I will be able to modify the email.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
public function index()
{
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
}
public function store(Request $request)
{
$user = new User();
$user->name = $request->get("name");
$user->email = $request->get("email");
$user->password = $request->get("password");
$user->save();
return response()->json($user->toArray(), 200);
}
public function show($id)
{
//
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
And my route:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('v1/users/create', 'UserController#store');
RESTful APIs made by me tests in Postman. Help me somebody
Looking at your question, I think you need to create a route to link to update method in your controller same way you created a post for creating user.
Route::put('v1/users/client/{id}', 'UserController#update);
OR you can use laravel predefined code to create all CRUD routes.
Route::resource('v1/users/client', 'UserController').
To view all the routes created, use
php artisan route:list
Have a further study on this.

Call to undefined relationship [user_id] on model [App\User]

I'm trying Laravel 5.4 (i usually work with 5.1) and im actually copypasting most of the code, so i dont understand what is the trouble, maybe is because there is a better way to do it but yeah, its been 1 hour and i cant get past this;
Hope you can help me with this..
In case this isn't enough i'll be posting my views and routes. Thank to everyone.
This is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = ['user_id', 'user_name', 'user_birthday'];
public static $rules = [
'user_name' => 'required|max:255',
'user_birthday' => 'required'
];
public $timestamps = false;
}
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UsersController extends Controller
{
public function index()
{
$users = User::with('user_id')->orderBy('user_id', 'ASC')->paginate(10);
return view('admin.users.index')->with("user", $users);
}
public function create()
{
return view('admin.users.create');
}
public function store(Request $request)
{
$users = new User($request->all());
$users->save();
return redirect()->route('admin.users.index');
}
public function show($id)
{
$users = User::find($id);
}
public function edit($id)
{
$users = User::find($id);
return view('admin.users.edit')->with('user', $user);
}
public function update(Request $request, $id)
{
$users = User::find($id);
$users->user_name = $request->user_name;
$users->user_birthday = $request->user_birthday;
$users->save();
return redirect()->route('admin.users.index');
}
public function destroy($id)
{
$users = User::find($id);
$users->delete();
return redirect()->route('admin.users.index');
}
}
Your error is from the following line of code. When you use with on a model is to load children relationships or sub-models. That is why the application is looking for the relationship user_id in the User Model thinking that it's a sub-model of the User model but it's not, so it return an error.
wrong
$users = User::with('user_id')->orderBy('user_id', 'ASC')->paginate(10);
correct
$users = User::orderBy('user_id', 'ASC')->paginate(10);

Laravel POST method going to GET

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(){

How to call controller action in Laravel and run validation request

I have a groups table in my database and each group has a slug. I have the following routes defined last in my routes.php file so that if no other URL is matched the app checks whether the slug belongs to a group and shows the group page instead. There is also a form on the group page so the submission of this form needs to be handled as well.
Route::get('{slug}', ['as' => 'dynamic_route', function($slug){
$group = \App\Group::where('slug', $slug)->first();
if(!is_null($group)) {
$app = app();
$controller = $app->make('App\Http\Controllers\GroupsController');
return $controller->callAction('view', ['slug' => $group->slug]);
} else {
abort(404);
}
}]);
Route::post('{slug}', ['as' => 'dynamic_route_submit', function($slug){
$group = \App\Group::where('slug', $slug)->first();
if(!is_null($group)) {
$app = app();
$controller = $app->make('App\Http\Controllers\GroupsController');
return $controller->callAction('handle_register', [$group->slug]);
} else {
abort(404);
}
}]);
Here is my groups controller:
<?php namespace App\Http\Controllers;
use View;
use App\Group;
use App\Lifestyle_question;
use App\Http\Requests\User\RegisterStep1Request;
use App\Http\Requests\User\RegisterStep2Request;
use Breadcrumbs;
class GroupsController extends FrontendController {
public function __construct()
{
parent::__construct();
}
function view($slug)
{
$this->data['group'] = Group::where('slug', '=', $slug)->first();
$this->data['lifestyle_questions'] = Lifestyle_question::all();
Breadcrumbs::setCurrentRoute('dynamic_route', $this->data['group']);
return View::make('groups/view', $this->data);
}
function handle_register(RegisterStep1Request $request1, RegisterStep2Request $request2, $slug)
{
$this->data['group'] = Group::where('slug', '=', $slug)->first();
die("Validation passed");
}
}
The view method works fine however when I submit the form I get the following error message:
ErrorException in GroupsController.php line 27:
Argument 1 passed to App\Http\Controllers\GroupsController::handle_register() must be an instance of App\Http\Requests\User\RegisterStep1Request, string given
I know this has to do with the parameters that are being passed to the controller method from the route definition and so I tried the following in an attempt to sort it:
Route::post('{slug}', ['as' => 'dynamic_route_submit', function($slug){
$group = \App\Group::where('slug', $slug)->first();
if(!is_null($group)) {
$app = app();
$controller = $app->make('App\Http\Controllers\GroupsController');
return $controller->callAction('handle_register', [new \App\Http\Requests\User\RegisterStep1Request, new \App\Http\Requests\User\RegisterStep2Request, $group->slug]);
} else {
abort(404);
}
}]);
This fixed the issue except the requests just didn't get triggered. How can I call this method and ensure that the requests get triggered so that the validation is run?
Never use an anonymous function in the routing if you're going to call a controller inside of it. Declare your route like this:
Route::post('{slug}', ['as' => 'dynamic_route_submit', 'uses' => 'App\Http\Controllers\GroupsController#handle_register']);
Then in the controller handle whatever validation is necessary.
You could try moving your request validations out of the Request classes and into private controller actions:
UserController.php
/**
* Validates a Create User request
*/
protected function validateCreate()
{
$this->validate($this->request, [
'name' => 'required|max:255',
'email' => 'required|unique:users|max:255',
'account_types_id' => 'required|numeric',
]);
}
So do something similar with your code and call these validation methods from within your controller action:
UserController.php
/**
* #return \Illuminate\Http\RedirectResponse
* #throws CreateException
*/
public function create()
{
$this->validateCreate();
As an FYI you can access route parameters by name using request()->route()->getParameter('slug')
$slug = request()->route()->getParameter('slug');
$this->data['group'] = Group::where('slug', '=', $slug)->first();

Categories