Laravel - Paramaters should be how when we use match route? - laravel

I want to use match method but I can't take $slug and $request in controller..
Here is my route
Route::match(['get','post] , 'category/{slug}' , ['as'=>'category.show' , 'uses'=>'CategoryController#categoryProducts'])
in Controller, our function will be how ? How we use that post and get data in the same function ? I tried like below, but dosen't work
public function categoryProducts($slug, $request) {
//codes
}

Please use Request::method();
public function categoryProducts(Request $request, $slug) {
//codes
}
to get request type GET/POST
$method = Request::method();
or
if (Request::isMethod('post'))
{
//
}

Since you're trying to inject Request object and not passing it, do this instead:
public function categoryProducts(Request $request, $slug)

Related

use pagination in laravel api resource in laravel

I want to use pagination after getting my data from api resource
But the server responds:
Method Illuminate\Database\Eloquent\Collection::pagination does not exist.
public function index(Request $request )
{
$perPage=$request->per_page;
return response()->json(['user'=>UserResource::collection(User::with('roles')->get()->pagination($perPage))],200);
}
You don't have to call paginate on get function
Just
public function index(Request $request ) {
$perPage=$request->per_page;
return response()->json(['user'=>UserResource::collection(User::with('roles')->pagination($perPage))],200);
}
Even Better
public function index(Request $request ) {
$perPage=$request->per_page;
return new UserCollection(User::with('roles')->paginate($perPage));
}
return response()->json(['user'=>UserResource::collection(User::paginate($perPage))],200);
this is worked correctly !
100% ok

modify getRouteKeyName in Laravel 5.7

I defined slug for single DB in a column of structure DB. When I will call the slug in route, Could I get slug from another model (e.g. structure here) in route?
The route is:
localhost:8000/api/singles/firstTest
I defined getRouteKeyName function in Single model:
public function structure()
{
return $this->belongsTo(Structure::class);
}
public function getRouteKeyName()
{
return $this->structure()->select('slug')->first();
}
In your controller you will get the firstTest as route param if you have specified route as :
Route::get('api/singles/{slug}', 'SomeController#someAction');
Then controller :
public function someAction(Request $request, $slug)
{
// Perform validations and policy authorization if required
$id = Single::whereHas('structure', function ($query) use($slug) {
$query->where('slug', '=', $slug);
})->first();
if(!$id){
abort(404);
}
// Process the data using $id obtained above
}

Laravel 5 - How to passing request data from route to controller

I am new in laravel,
How to passed request data into controller ? Just like happen on view ?
Route::get('/kelihatan', function (Request $request) {
return view( 'pages' , [ 'page' => 'index' , '_request' => $request->all() ] );
});
How to passing request data to controller before passed into view or model ? Just like this ??
Route::get( '/{page}', 'UserController#show' );
Mention the path in route first depending upon the type of request i.e. Get or Post
Route::get('/invite/{code}', 'MyController#get_my_action');
Route::post('/invite/{code}', 'MyController#post_my_action');
Then in controller named as MyController create a function like
public function get_my_action($code){
//your code goes here
}
or
public function post_my_action(Request $request, $code)
{
//your code goes here
}
With that route:
Route::get('/{page}', 'UserController#show');
In the controller you can do that:
public function show()
{
$page = request()->route('page');
or that:
public function show($page)
or that:
public function show(Request $request, $page)
Try this:
Routes.php
Route::get( '/{page}', 'UserController#show' );
UserController.php
public function show($page) {
dd($page);
}
Inside your controller define your show function as below:
function show(Request $request)
{
echo $request['page'];//or whatever data you want to pass
}
///add follwoing line before you define controller
use Illuminate\Http\Request;

Handling Custom Exceptions from PHPUnit (Laravel 5.2)

I'm currently playing around with Exception Handler, and creating my own custom exceptions.
I've been using PHPUnit to run tests on my Controller Resource, but when I throw my custom exceptions, Laravel thinks it's coming from a regular HTTP request rathen than AJAX.
Exceptions return different response based on wether it's an AJAX request or not, like the following:
<?php namespace Actuame\Exceptions\Castings;
use Illuminate\Http\Request;
use Exception;
use Actuame\Exceptions\ExceptionTrait;
class Already_Applied extends Exception
{
use ExceptionTrait;
var $redirect = '/castings';
var $message = 'castings.errors.already_applied';
}
And the ExceptionTrait goes as follows:
<?php
namespace Actuame\Exceptions;
trait ExceptionTrait
{
public function response(Request $request)
{
$type = $request->ajax() ? 'ajax' : 'redirect';
return $this->$type($request);
}
private function ajax(Request $request)
{
return response()->json(array('message' => $this->message), 404);
}
private function redirect(Request $request)
{
return redirect($this->redirect)->with('error', $this->message);
}
}
Finally, my test goes like this (excerpt of the test that's failing)
public function testApplyToCasting()
{
$faker = Factory::create();
$user = factory(User::class)->create();
$this->be($user);
$casting = factory(Casting::class)->create();
$this->json('post', '/castings/apply/' . $casting->id, array('message' => $faker->text(200)))
->seeJsonStructure(array('message'));
}
My logic is like this although I don't think the error is coming from here
public function apply(Request $request, User $user)
{
if($this->hasApplicant($user))
throw new Already_Applied;
$this->get()->applicants()->attach($user, array('message' => $request->message));
event(new User_Applied_To_Casting($this->get(), $user));
return $this;
}
When running PHPUnit, the error I get returned is
1) CastingsTest::testApplyToCasting PHPUnit_Framework_Exception:
Argument #2 (No Value) of PHPUnit_Framework_Assert:
:assertArrayHasKey() must be a array or ArrayAccess
/home/vagrant/Code/actuame2/vendor/laravel/framework/src/Illuminate/Foundation/T
esting/Concerns/MakesHttpRequests.php:304
/home/vagrant/Code/actuame2/tests/CastingsTest.php:105
And my laravel.log is over here http://pastebin.com/ZuaRaxkL (Too large to paste)
I have actually discovered that PHPUnit is not actually sending an AJAX response, because my ExceptionTrait actually changes the response on this. When running the test it takes the request as a regular POST request, and runs the redirect() response rather than ajax(), hence it's not returning the correspond.
Thanks a bunch!
I have finally found the solution!
As I said, response wasn't the right one as it was trying to redirect rathen than return a valid JSON response.
And after going through the Request code, I found out that I need to use also wantsJson(), as ajax() may not be the case always, so I have modified my trait to this:
<?php
namespace Actuame\Exceptions;
trait ExceptionTrait
{
public function response(Request $request)
{
// Below here, I added $request->wantsJson()
$type = $request->ajax() || $request->wantsJson() ? 'ajax' : 'redirect';
return $this->$type($request);
}
private function ajax(Request $request)
{
return response()->json(array('message' => $this->message), 404);
}
private function redirect(Request $request)
{
return redirect($this->redirect)->with('error', $this->message);
}
}

Laravel 5 : get route parameter in Controller 's constructor

I defined routes for a controller this way :
/model/{id}/view
/model/something/{id}/edit
I need to get the id parameter in the contructor of this controller. For example :
class ArtController extends Controller {
public function __construct(Request $request){
//dd($this->route('id')); //Doesn't work
//dd($request->segments()[1]); //this works for the first route but not the second
}
}
How can you get the parameter id in the constructor of a Controller in Laravel?
You should be able to do something like this
$id = Route::current()->getParameter('id');
Update:
Starting in laravel 5.4 getParameter was renamed to parameter
$id = Route::current()->parameter('id');
public function __construct(Request $request)
{
$id = $request->route('id');
dump($id);
}
You can call anywhere:
request()->route('id');
No need for injection
not use segments
use segment
public function __construct(Request $request){
dd($request->segment(1));}

Resources