Laravel.54 pass data to action controller - laravel

I need to get 'mp3' value in controller !
( to check posts from mp3s type )
my post types :
video, album , mp3
(web.php)
Route::group(array('prefix' => 'mp3s'), function($pt) {
Route::get("/", "PostController#archivePosts");
Route::get("mp3/{slug}", "PostController#singlePost");
});
Route::group(array('prefix' => 'albums'), function($pt) {
Route::get("/", "PostController#archivePosts");
Route::get("album/{slug}", "PostController#singlePost");
});
Route::group(array('prefix' => 'videos'), function($pt) {
Route::get("/", "PostController#archivePosts");
Route::get("video/{slug}", "PostController#singlePost");
});

#danial dezfooli
To Get Prefix value you can inject Request Dependency inside controller's method as below.
public function index(\Illuminate\Http\Request $request){
dd($request->route()->getPrefix());
}
or you can do in another way also
public function index(){
dd($this->getRouter()->getCurrentRoute()->getPrefix());
}
For more reference you can refer : Laravel 5 get route prefix in controller method

Route::get("mp3/{slug}", "PostController#singlePost");
In PostController, you can get it like
public function singlePost($slug) {
dd($slug)// to check slug value
}

Related

Laravel - how to add variable type to parameter of controller method

I have a controller method that has a parameter. I need to add a type to it:
public function deleteIndex(int $user_id)
{
return DB::try(function () use ($user_id) {
if (empty($user_id)) {
return error(trans('user.invalid_data_recheck'));
}
$user = User::find($user_id);
if (empty($user)) {
return error(trans('user.invalid_user'));
}
if (!$user->delete()) {
return error(trans('user.could_not_delete_user'));
}
return success();
});
}
The route looks like this:
AdvancedRoute::controllers([
'users' => 'API\UserAPIController'
]);
From the JS the parameter is being sent like this: '/users/{user_id}'
The issue I have is, when I add the parameter type: "int" in the controller method, the endpoint is no longer reached, if I remove "int" everything works fine. But I need that for an openapi library that I use. Any help is appreciated!

How I can make route API in Laravel with parameter

my route:
Route::get('page/{key_id_fk}', 'PagesApiController#show');
my function:
public function show($key_id_fk)
{
$sub=DefintionDetails::find($key_id_fk);
// $main=Definition::where([['type','=',1],['available','=',1],['id_definition','=',$sub->id_def]])->get();
return response()->json($sub , 200);
}
on post man route is page?key_id_fk=1 give error 404 not found key in data base but didn't read.
You should be accessing page/1 rather than page?key_id_fk=1 as you are not using parameter queries in your request url.
Your route format is page/$key_id_fk.
In the route file:
Route::get('page/{key_id_fk}', 'PagesApiController#show');
In the controller:
public function show($key_id_fk){
$sub = DefintionDetails::find($key_id_fk);
if($sub){
return response()->json(['success' => true, 'sub' => $sub]);
} else {
return response()->json(['success' => false, 'error_message' => 'No data found!']);
}
}
Your postman route:
http://example.com/page/1
You are setting key_id_fk as http://example.com/page/1 in route and passing parameter as http://example.com/page?key_id_fk=1 difference is first one is URL route data and second is GET parameter data to get data from URL route you have this public function show($key_id_fk) and to get data from GET parameter public function show(Request $request) and $request->key_id_fk.
so change URL to this http://example.com/page/1 format
or
change getting method in the controller to public function show(Request $request) and $request->key_id_fk

Passing route parameter to controller Laravel 5

I'm trying to pass a route parameter to controller, but I get this error : Argument 2 passed to App\Http\Controllers\JurnalController::store() must be an instance of App\Http\Requests\JurnalRequest, none given
Below are the codes ..
Route :
Route::get('/edisi/{id}', 'JurnalController#store');
Controller :
public function store($id, JurnalRequest $request) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
$jurnal = Edisi::findOrFail($id)->jurnal()->create($input);
return redirect('jurnal');
}
So my question is how to pass the route parameter properly ? Thank you
new routes :
Route::get('/', function () {
return view('pages/home');
});
Route::group(['middleware' => ['web']], function () {
Route::get('edisi', 'EdisiController#index');
Route::get('edisi/create', 'EdisiController#create');
Route::get('edisi/{edisi}', 'EdisiController#show');
Route::post('edisi', 'EdisiController#store');
Route::get('edisi/{edisi]', 'EdisiController#edit');
Route::patch('edisi/{edisi}', 'EdisiController#update');
Route::delete('edisi/{edisi}', 'EdisiController#destroy');
});
Route::get('/edisi/{id}', 'JurnalController#storejurnal');
Route::group(['middleware' => ['web']], function () {
Route::get('jurnal', 'JurnalController#index');
Route::get('jurnal/create', 'JurnalController#create');
Route::get('jurnal/{jurnal}', 'JurnalController#show');
Route::post('jurnal', 'JurnalController#storejurnal');
Route::get('jurnal/{jurnal}/edit', 'JurnalController#edit');
Route::patch('jurnal/{jurnal}', 'JurnalController#update');
Route::delete('jurnal/{jurnal}', 'JurnalController#destroy');
});
new storejurnal method :
public function storejurnal(JurnalRequest $request, $id) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$jurnal = Edisi::findOrFail($id)->jurnal()->create($input);
return redirect('jurnal');
}
When you are using resource controller, the store method does not accept any other argument except the Request instance. Try changing the method name or remove the second argument. store() method be default accepts post requests not get requests. Either put your route on top of the resource controller or change the method name.
Route::get('/edisi/{id}', 'JurnalController#store');
Route::resource('jurnals', 'JurnalController');
I hope this helps.
The correct format is:
public function store(JurnalRequest $request, $id) {
// your code
}
If you receive an argument such as Missing argument 2 as suggested in your comments, it means that either you aren't generating the routes correctly, or the url doesn't include the id segment.

Laravel - Change URL parameters using GET

I have RESTful API built on Laravel.
Now I'm passing parameter like
http://www.compute.com/api/GetAPI/1/1
but I want to pass parameter like
http://www.compute.com/api/GetAPI?id=1&page_no=1
Is there a way to change Laravel routes/functions to support this?
you can use link_to_route() and link_to_action() methods too.
(source)
link_to_route take three parameters (name, title and parameters). you can use it like following:
link_to_route('api.GetAPI', 'get api', [
'page_no' => $page_no,
'id' => $id
]);
If you want to use an action, link_to_action() is very similar but it uses action name instead of route.
link_to_action('ApiController#getApi', 'get api', [
'page_no' => $page_no,
'id' => $id
]);
href text
with these methods anything after the expected number of parameters is exceeded, the remaining arguments will be added as a query string.
Or you can use traditional concatination like following:
create a route in routes.php
Route::get('api/GetAPI', [
'as' => 'get_api', 'uses' => 'ApiController#getApi'
]);
while using it append query string like this. you can use route method to get url for required method in controller. I prefer action method.
$url = action('ApiController#getApi'). '?id=1&page_no=1';
and in your controller access these variables by following methods.
public function getApi(Request $request) {
if($request->has('page_no')){
$page = $request->input('page_no');
}
// ...your stuff
}
Or by Input Class
public function getApi() {
if(Input::get('page_no')){
$page = Input::get('page_no');
}
// ...your stuff
}
Yes you can use those parameters, then in your controllers you can get their values using the Request object.
public function index(Request $request) {
if($request->has('page_no')){
$page = $request->input('page_no');
}
// ...
}

Laravel 5: How to create a router model binding on multiple parameters

So far I know how to create a router model binding on single parameters like so:
// RouteServiceProvider.php
$router->model('subject_slug', 'App\Subject', function($slug) {
return Subject::where('slug', $slug)->firstOrFail();
});
The above can then be used like this:
// routes.php
Route::get('/{subject_slug}', 'MenuController#showSubject');
And in the controller:
public function showSubject(Subject $subject) {
....
}
But sometimes I need to specify multiple parameters in order to get the right model.
For example consider the following route:
Route::get('/{subject_slug}/{topic_slug}/', 'MenuController#showTopic');
and the corresponding controller:
public function showTopic(Subject $subject, Topic $topic) {
....
}
However to get the correct model for Topic I need to know the Subject. For example:
// !!! Invalid laravel code !!!
$router->model('topic_slug', 'App\Topic, function($subject_slug, $topic_slug) {
// ERROR: $subject_slug is obviously not defined!
return Topic::where([
'subject_slug' => $subject_slug,
'slug' => $topic_slug,
])->firstOrFail();
});
How can I make a router model binding for Topic bearing in mind I need to know the Subject parameter before it in order to fetch the correct Topic.
Is there an alternative better way of doing this?
UPDATE
Currently my showTopic method in my controller is like this:
public function showTopic(Subject $subject, $topic_slug) {
$topic = Topic::where([
'subject_slug' => $subject_slug,
'slug' => $topic_slug,
])->firstOrFail();
// ...
}
and I have no router model binding for topic_slug.
This works as expected, but I would like to take advantage of router model bindings!
It turns out the way I was doing it was a bit flawed. I was unnessarily using model bindings when instead it would be better to have used a normal binding like so:
$router->bind('topic_slug', function($slug, Route $route) {
$subject = $route->parameter('subject_slug');
return Topic::where([
'subject_slug' => $subject->slug,
'slug' => $slug,
])->firstOrFail();
});
Also I was using model bindings completely wrong before as the 3rd function should be the "not found behaviour" (not for additional logic)!

Resources