GET parent id in nested resource - php

Im trying to get all comments under post #{any nos.} , but I'm stuck on how can I get the post_id when I hit the URI below. for example post #1
on GET URI : /posts/1/comments/
on CommentController :
public function actions() {
$actions = parent::actions();
unset($actions['index']);
return $actions;
}
public function actionIndex($post_id)
{
return Comments::find()->where(['post_id' => $post_id])->all();
}

make use of _urlManager in yii2
return [
'class'=>'yii\web\UrlManager',
'enablePrettyUrl'=>true,
'showScriptName'=>false,
'rules'=>[
// url rules
'posts/<post_id:\d+>/comments' => 'posts/index',
]
];

Related

How to remove parameter from a URL in laravel 5.2

How can I remove the parameters from a URL after processing in my controller? Like this one:
mydomain/mypage?filter%5Bstatus_id%5D
to
mydomain/mypage
I want to remove the parameters after the ? then I want to use the new URL in my view file. Is this possible in laravel 5.2? I have been trying to use other approaches but unfortunately they are not working well as expected. I also want to include my data in my view file. The existing functionality is like this:
public function processData(IndexRequest $request){
//process data and other checkings
return view('admin.index')
->with([
'data' => $data,
'person' => $persons,
]);
}
I want it to be like:
public function processData(IndexRequest $request){
//process data and other checkings
// when checking the full url is
// mydomain/mypage?filter%5Bstatus_id%5D
// then I want to remove the parameters after the question mark which can be done by doing
// request()->url()
// And now I want to change the currently used url using the request()->url() data
return view('admin.index')
->with([
'data' => $data,
'person' => $persons,
]);
}
I'm stuck here for days already. Any inputs are appreciated.
You can use request()->url(), it will return the URL without the parameters
public function processData(IndexRequest $request){
$url_with_parameters = $request()->url();
$url= explode("?", $url_with_parameters );
//avoid redirect loop
if (isset($url[1])){
return URL::to($url[0]);
}
else{
return view('admin.index')
->with(['data' => $data,
'person' =>$persons,]);
}
}
add new url to your routes and assuming it will point to SomeController#SomeMethod, the SomeMethod should be something like :
public function SomeMethod(){
// get $data and $persons
return view('admin.index')
->with(['data' => $data,
'person' =>$persons,]);
}
I hope this helps

Type error: Argument 2 passed to Controller::show() must be an instance of modal, string given

Adding up and down voting functions to a classified page. Using Laravel, and Vue.
The error I get is:
(1/1) FatalThrowableError
Type error: Argument 2 passed to Hustla\Http\Controllers\ListingVoteController::show() must be an instance of Hustla\Listing, string given
I have included the vue file, the vote controller, the listing model, and the route. I was hoping someone could help me out.
Listing Model
public function votesAllowed()
{
return (bool) $this->allow_votes;
}
public function commentsAllowed()
{
return (bool) $this->allow_comments;
}
public function votes()
{
return $this->morphMany(Vote::class, 'voteable');
}
public function upVotes()
{
return $this->votes()->where('type', 'up');
}
public function downVotes()
{
return $this->votes()->where('type', 'down');
}
public function voteFromUser(User $user)
{
return $this->votes()->where('user_id', $user->id);
}
Vote Controller
public function show(Request $request, Listing $listing)
{
$response = [
'up' => null,
'down' => null,
'can_vote' => $listing->votesAllowed(),
'user_vote' => null,
];
if ($listing->votesAllowed()) {
$response['up'] = $listing->upVotes()->count();
$response['down'] = $listing->downVotes()->count();
}
if ($request->user()) {
$voteFromUser = $listing->voteFromUser($request->user())->first();
$response['user_vote'] = $voteFromUser ? $voteFromUser->type : null;
}
return response()->json([
'data' => $response
], 200);
}
Vote.vue
<template>
<div class="listing__voting">
<a href="#" class="listing__voting-button">
<span class="glyphicon glyphicon-thumbs-up"></span>
</a> 1
<a href="#" class="listing__voting-button">
<span class="glyphicon glyphicon-thumbs-down"></span>
</a> 2
</div>
</template>
<script>
export default {
data () {
return {
up: null,
down: null,
userVote: null,
canVote: false
}
},
props:{
listingId: null
}
}
</script>
Route
Route::get('/{location}/{listing}/votes',[
'uses' => '\Hustla\Http\Controllers\ListingVoteController#show'
]);
Your route definition has two parameters defined: {location} and {listing}. The parameters are passed to the controller method in the order in which they are defined.
Your controller method, however, is only defined to accept one route parameter. The first route parameter is what will be passed to the method, and in this route definition, that is the {location} parameter. Since {location} does not match $listing, the string value will be passed in, and you'll get the error you're seeing.
You need to add the second route parameter to your controller action:
public function show(Request $request, $location, Listing $listing)
{
// code
}
If $location is a model as well, you can go ahead and add the type hint to enable the implicit route model binding.

How can I get the list of required parameters of a yii 2.0 action as an array?

When a user visits a particular url in my yii 2.0 application without required parameters, I want to present a form to collect the required missing parameters.
for this purpose, I need the names of missing parameters, e.g. I have a function
public function actionBlast ($bomb, $building) {
}
I expect the results as an array like this
$args = [0=>'bomb', 1=>'building'];
I tried func_get_args() but it returns null, and the undocumented ReflectionFunctionAbstract::getParameters ( void ) etc. Any other way out?
I think the best way to achieve what you want is to override the default ErrorAction.
Inside your controllers directory, create:
controllers
actions
ErrorAction.php
In ErrorAction.php, add:
<?php
namespace frontend\controllers\actions;
use Yii;
use yii\web\ErrorAction as DefaultErrorAction;
class ErrorAction extends DefaultErrorAction
{
public function run()
{
$missing_msg = 'Missing required parameters:';
$exception = Yii::$app->getErrorHandler()->exception;
if (substr($exception->getMessage(), 0, strlen($missing_msg)) === $missing_msg) {
$parameters = explode(',', substr($exception->getMessage(), strlen($missing_msg)));
return $this->controller->render('missing_params_form' ?: $this->id, [
'parameters' => $parameters,
]);
}
return parent::run();
}
}
In your controller add:
public function actions()
{
return [
'error' => [
'class' => 'frontend\controllers\actions\ErrorAction',
],
];
}
and create a view "missing_params_form.php" in your controller `s view directory, where you can generate your form fields.
I believe this to be your best option, though you may need to update it in case a Yii update changes the error message.

laravel - Ajax Post says NotFoundHttpException

I am new to laravel. Recently I cloned sample project from github. I try to do curd operation. when I post the data I get
{"error":"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException","message":"","file":"\/home\/sq1\/lampstack-5.5.28\/apache2\/htdocs\/app\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/RouteCollection.php","line":145}}
Routes.php
Route::group
(
[
'prefix' => '/executive/ajax',
],
function ()
{
Route::get
(
'get-executive',
'LeadExecutiveController#getLeadExecutives'
);
Route::get
(
'get-executive/{sponsorID}',
'LeadExecutiveController#getLeadExecutiveData'
);
);
Route::resource('/executive' ,'ExecutiveController');
ExecutiveController.php
public function store() //I think store action should work here
{
...
}
public function destroy($id)
{
...
}
public function getLeadExecutiveData($leadExecutiveID)
{
...
}
public function update($leadExecutiveID)
{
...
}
Ajax Url : http://localhost:8080/app/public/deal/executive
Post parameters:
_token : WXv5u4zYkANnnWidTciFN8HVrz2ARECe669Kwvqn
first_name : test
last_name : test
You are posting to deal/executive, but your resource set to executive.
Change your router to:
Route::resource('deal/executive' ,'ExecutiveController');

How to filter records with RESTful models and controllers in Yii2

I'm creating a RESTful API with Yii2 and have successfully setup a model named Contacts by following the Quick Start Tutorial*. I love how records can be created, listed, updated and deleted without creating any actions.
However I can't see how to filter results. I would like to only return contacts where contact.user_id is equal to 1 (for example) as it currently will reply with all records. Is this possible without creating the actions?
I am unsure also how I can limit results. From what I've read I feel it should append the URI with ?limit=5.
http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html
You should return a dataprovider instead of a set of objects, that supports pagination for you.
Perhaps this approach will be a bit more useful:
public function actionIndex()
{
return new \yii\data\ActiveDataProvider([
'query' => Contact::find()->where(['user_id' => \Yii::$app->user-id]),
]);
}
You could also leave the index action intact, but provide the preset action with a prepareDataProvider-callback:
public function actions()
{
$actions = parent::actions();
$actions['index']['prepareDataProvider'] = function($action)
{
return new \yii\data\ActiveDataProvider([
'query' => Contact::find()->where(['user_id' => \Yii::$app->user-id]),
]);
};
return $actions;
}
Hope that helps.
I have had to override the index method despite not wanting to. My solution looks like this:
public function actions()
{
$actions = parent::actions();
unset($actions['index']);
return $actions;
}
public function actionIndex()
{
return Contact::findAll(['user_id' => \Yii::$app()->user-id]);
}
I guess this solution means I need to write my own pagination code however which is something else I was hoping to avoid.

Categories