laravel and vue, loading view without expected prop - php

I asked a question about this earlier but I'm still stuck and having some issues.
Right now, if I go to site.com/status/12345 then I will get my status as I would expect. The route with the id (12345) hits a controller method which passes that id in and returns the json version of it in the view, where I'm using it as a prop and calling a function with it on page load.
However, if I just go to site.com/status (which should hit my index method, returning only the base view) then I get 'undefined variable entryKey'.
Obviously, I'm adding my entryKey value from the controller into my blade to be passed in as a prop, which seems to be working if there is a URL segment for it, but now I can't just get my base view to return with site.com/status
How can I fix this so that site.com/status hits my index method and site.com/status/12345 hits the detail method and passes the id in as a prop?
web.php (routes)
Route::get('/entry/status', 'entry\entryController#index')
->name('entry.status');
Route::get('/entry/status/{id}', 'entry\entryController#details')
->name('entry.status');
controller.php
public function index() {
return view('entry.status');
}
public function details($id) {
if (request()->wantsJson()) {
return json_encode(entry::getDetails($id));
}
$entryID = json_encode($id);
return view('entry.status')
->with('entryKey', $entryID);
}
status.blade.php
<entry-dashboard :entry-key="{{$entryKey}}"></entry-dashboard>
detail.vue
props: [
'entryKey'
],
created() {
this.setDetailWindow(this.entryKey);
},
setDetailWindow(event) {
this.detailId = event.taskt_id;
axios.get('/entry/status/' + this.detailId)
.then(response => {
...
...
}

Related

Laravel route when where condition is false

I have the next code:
Route::get('/{lang}/user/sort-by-{class}', function ($lang,$class) {
return view('users.list',compact("lang","class"));
})->where('class', '[a-z]+');
Route::get('/{lang}/user/{user}', function ($lang,$user) {
return view('users.user',compact("lang","user"));
});
When condition in where is false, how can I send it directly to 404 when sort-by- is for example a number? The problem is that it goes to secondary route as an user.
For example:
/en/user/sort-by-name is ok
/en/user/sort-by-4446 must show 404 page
I know that i can do another route just between them with
Route::get('/{lang}/user/sort-by-{class}', function ($lang,$class) {
return \Response::view('errors.404',array(),404);
})->where('class', '.*');
but this seems ugly, i would like in same sentence
Basically, you may do this
Route::get('/{lang}/user/sort-by-{class}', function ($lang,$class) {
if (is_numeric($class)) {
abort(404, 'Your reason');
}
return view('heros.list',compact("lang","class"));
});
Though, using closures in routes is a bad practice because they cannot be serialized in production mode. That's why you should use a controller to return your view, and assign a middleware to this route which will check your class and abort the request if needed.

Vue, sharing blade/view with two routes

I'm very stuck here and I'm not sure the best course of action
Currently I have a blade and vue component that make up a dashboard. I have one route that loads the view for the dashboard, and another route (which is called inside the dashboard upon an event) which gets details for an ID.
This works perfectly right now.
The issue is that I want to be able to hit that 2nd route externally (like site.com/status/12345) and load the data for that id (12345) by default.
Right now I hit site.com/status and on page creation it calls fetchEntries to get data, I render a table based on that data with links, so if you click a link it passes the ID for that clicked entry into status/{id} to get details for that specific clicked entry. THen it loads the returned data into a details screen.
All I want to do here is make it so that if I call status/12345 it hits that route, and my controller details method. I know I can call that function on page creation as well, but I want to know how to handle the difference between site.com/status and site.com/status/12345.
What should I do here, and how do I go about it?
Here's what I have right now:
controller.php
public function index() {
return view('Entry.status');
}
public function details($id) {
return json_encode(Entry::getDetails($id));
}
web.php (route)
Route::get('/Entry/status', 'Entry\EntryController#index')
->name('Entry.status');
Route::get('/Entry/status/{id}', 'Entry\EntryController#details')
->name('Entry.status');
status.vue
created() {
this.fetchEntries();
},
fetchEntries() {
axios.get('/Entry/dashboard')
.then(response => {
this.events = response.data;
})
.catch(function(error) {
console.log(error)
})
.finally(function() {
})
},
getDetails(event) {
this.detailId = event.taskt_id;
axios.get('/Entry/status/' + this.detailId)
.then(response => {
...
}
if I understand your question correctly. I think you can do something like this.
public function details($id) {
if (request()->wantsJson()) {
return json_encode(Entry::getDetails($id));
}
return view('Entry.detail');
}
Is it what you want?

How get lot of params from url but without (&)?

For now in Laravel i am testing url and in route i have
Route::group(['prefix' => 'game'], function (){
Route::get('/location/{location?}/action/{action?}/screen/{screen?}','GameController#index')->name('game.index');
});
In controller when i wanna pass params i have to type
example.com/game/location/1/action/update/screen/main
if i wanna pass only location and screen i have an error cause in url second param should be action.
I can create url like
example.com/game/?location=1&screen=main
and controller $request->screen and location works fine. But is any way to not using & ? and do this like:
example.com/game/location/1/screen/main
For this route
Route::get('/locations/{location?}/actions/{action?}/screens/{screen?}','GameController#index')->name('locations.actions.screens.show');
In GameController index method, you can get these parameter as
public function index(Location $location, Action $action, Screen $screen) {
// here you can use those models
}
if you are using route-model binding,
if not using
public function index($location, $action, $screen) {
// here you can use these variables
}
If the route name is locations.actions.screens.show then in view, it will be
Test
Now, if you have some query parameter
then it will be like $http://example.com/?test="some test data"&another_test="another test"
you can access these parameter like
public function myfunction(Request $request) {
dd($request->all());
}
Let's consider you want to retrieve all games, that belongs to a particular screen which belongs to a particular action and that belongs to a particular location, what your urls seems to be in your question, in that case, the url will be
Route::group(['prefix' => 'game'], function (){
Route::get('locations/{location?}/actions/{action?}/screens/{screen?}','GameController#index')->name('game.index');
});
url seems to be game/locations/1/actions/1/screens/1 where action and screen parameter can be optional
now in your controller index() method
public function index(Location $location, Action $action=null, Screen $screen=null) {
//using the model instance you received, you can retrieve your games here
}
Your error makes sense
URL second param should be action
because your route is with wild card location, action, screen
Route::group(['prefix' => 'game'], function (){
Route::get('/location/{location?}/action/{action?}/screen/{screen?}','GameController#index')->name('game.index');
});
To access this route you have to generate a URL with a wild card like
example.com/game/location/1/screen/main
and example.com/game/?location=1&screen=main not going to work because of your route URL and you can't access like $request->screen.
so your controller must be like
public function index($reuest, $location, $action, $screen){
}
You can directly access $location, $action, $screen and if you request something like
example.com/game/location/1/screen/main?param1=1&param2=2
Those are accessible through request like
$request->param1 and $request->param2
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:
Route::get('user/{name?}', function ($name = null) {
return $name;
});
you can use Pattern Based Filters
You may also specify that a filter applies to an entire set of routes based on their URI.
Route::filter('admin', function()
{
//
});
Route::when('admin/*', 'admin');

Error when trying to return Redirect in Laravel

When I submit a form in Laravel, the following controller method handles it:
public function update($id)
{
//handle input
return View::make('generic.success', ["message" => 'Data submitted successfully!']);
}
This works fine. However, instead of returning a view like above I'd like to return a redirect, because when I return the view directly, reloading the page resubmits the form.
So I tried to do this:
public function update($id)
{
//handle input
return Redirect::to('/success', ['message' => 'Data submitted successfully!']);
}
In my routes file I defined the success route:
Route::get('success', 'NotificationsController#success');
And set up a notification controller to display the view:
class NotificationsController extends BaseController {
public function success($message)
{
return View::make('generic.success', ["message" => $message]);
}
When I run the above code, I get the following error from Laravel:
InvalidArgumentException
The HTTP status code "1" is not valid.
I have no idea what this is supposed to tell me, and neither does Google apparently.
Can someone shed some light on this issue?
P.S.
Incidentally, being new to Laravel, I've noticed so far that Laravel's error reporting is very user-unfriendly, in that instead of telling me I have an issue with my router, or controller, or permissions, it displays these generic errors with no humane explanation of their cause. Is there a better way to troubleshoot problems in Laravel than relying on this?
For example, in the above incident, the error report points to this line of code...
public function setStatusCode($code, $text = null)
{
$this->statusCode = $code = (int) $code;
if ($this->isInvalid()) {
throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
}
...which is completely useless, as all it does is show me the code that printed the error itself.
The second parameter of the redirector's to() method is the HTTP status code that will be returned by the response, not data that will be passed along. Passing data when redirecting to GET routes can be done either via the query string or the session. The recommended solution here is to pass data via the current session using the with() method which passes that data for the next request. So in your case this would be the approach needed:
public function update($id)
{
return Redirect::to('/success')->with('message', 'Data submitted successfully!');
}
Then in your success method you can have this:
public function success($message)
{
return View::make('generic.success', ["message" => Session::get('message')]);
}
When in doubt always try checking the documentation first. The solution to this is explicitly stated in the Laravel Response Redirects Documentation.
Thanks a lot -Bogdan I found in the documentation that you post answer to my problem. In my case the solution was redirect to an action in a controller, like this...
return
\Redirect::action(
'PqrController#solicitud',
array($id)
)
->with(
'message',
'¡El estado de la solicitud ha sido actualizado correctamente!'
)
;
I redirect to a method in a controller, with one parameter array($id) and I put too in the session a message using ->with('message','Mensaje')

Pressing back in browser (laravel app) causes an error

It's so weird. When a user is logged out of my application, press back to the previous page, which is user/login I get this error:
{"error":
{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException",
"message":"Call to a member function with()
on a non-object","file":"\/home\/nicola\/projects\/pensions\/app\/controllers\/UserController.php",
"line":79}}
The page isn't being reloaded though. I put a die() in the application and it doesn't hit it, so the error must be being generated from the cached version. However when browsed to directly, there is no problem accessing user/login. It's only when pressing back.
line 72 is:
$this->layout->with($this->data);
Which basically means it is saying layout isn't an object.
Layout is made into a view object in the base controller: ` $this->layout = \View::make($this->layout);
EDIT `
//the function causing the error
public function getLogin ()
{
$this->data['page_title'] = 'user/login';
$this->layout->with($this->data);//line 72
$this->layout->content = \View::make('user.login', $this->data);
}
//function that makes the $layout an object in base controller
protected function setupLayout ()
{
if (!is_null($this->layout) && !\Request::ajax()) {
$this->layout = \View::make($this->layout);
}
}

Categories