rerouting after calling a function in Laravel 5 - php

I'm getting my feet wet with Laravel 5 and I need a little advice on Routing.
I'm running in to a problem over and over and I feel like I'm definitely not grasping the proper way to do this.
Lets say I have a route:
Route::post('viewarticles', 'LoginController#user_check_article_list');
This is where I am taken after I login.
This route shows me my articles that I can edit. On the page this route takes you to I have a list of articles and delete buttons next to them. When I click delete I have it linked to
delete/{{ $article->id }}
I then have a route:
Route::get('delete/{id}', 'ArticleController#deleteArticle');
Which then goes to this function:
public function deleteArticle(Request $request, $id) {
$article = Article::find($id);
$article->delete();
$articles = Article::latest('published_at')->Published()->get();
return view('admin.article_edit_list',['articles'=>$articles]);
}
The last two lines of this is me rebuilding that article list and then loading the view.
THE PROBLEM: In my url the page is still ../delete/someid
I really just need a way to transfer back to the routes.

Instead of returning a view, return a redirect. This will cause the url to change:
public function deleteArticle(Request $request, $id)
{
$article = Article::find($id);
$article->delete();
return redirect('/some-url');
}
Or if using named routes:
return redirect()->route('some.route.name');
Source

so if your url is staying at /delete/{id} you need to redirect to the the display articles view
public function deleteArticle(Request $request, $id) {
$article = Article::find($id);
$article->delete();
return \Redirect::to('show_articles.view');
}

how do you send the delete request ? is it via ajax?
if so you need to redirect to your view in the success method of your ajax call using js / most likely jQuery?
.success(function(){
location.href = '/your/new/view';
});
its worth checking your variables are getting through to your controller as well
public function ...
echo $id; exit(); // or dd($id);
and checking your collection loaded
$articles = ...
dd($artcles);
retrun view(...
also if you go in to app/config/app.php and set debug=true you should get an error stack which will help debug the issue. Sorry for the delay internet went down before I could finish typing.

Related

displaying a view immediately after the 'store' resource controller in laravel

so at the moment my 'store' resource controller adds to the table in my database and fetches the view for my 'index' page (my home page) however when i refresh this view it duplicates the last row added to the database. i have noticed the URI is 'http://127.0.0.1:8000/store' instead of 'http://127.0.0.1:8000/index' can someone please explain what is going on. i apologise for the lack of technical terms i'm a new apprentice and am trying to figure this out using my own initiative but so far have had no luck. i also noticed that my log out function does the same thing although the URI is slightly different in that it still displays the CSRF token in the URI however it still says its at the 'logout' file path, here is an example of this; 'http://127.0.0.1:8000/logout?_token=bqTl4J3EZyKj7LS5ZvqfRB8k1Qg02IT1j4WlBG51&dir2login='
FYI i have already tried return $this->index();
my logout controller method;
public function logout(){
Auth::logout();
return view('index',['posts'=>$this->getTable()]);
}
my store controller method:
public function store(Request $request){
//creates new row in database table
//$clientIp=$request->ip();
$post = new PostModel();
//gets email of user currently logged in
$post->email=Auth::user()->email;
$post->ip=$request->ip();
$post->content=$request->content;
$post->company=$request->company;
$post->rating=$request->rating;
//saves to database
$post->save();
return view('index',['posts'=>$this->getTable()]);
}
Have you tried
return redirect('/');
What you're trying to do here is get the user to the index view. However, instead of returning a different view (and having to define the logic of 'posts' again), it's much easier to redirect the user to the index method of your controller. You have multiple options to do so. I have three listed below:
This is what you currently have:
return view('index',['posts'=>$this->getTable()]);\
you could do with the "action" (ControllerName#FunctionName):
return redirect()->action('PostController#index');
or with a "named route":
return redirect()->route('posts.index');
or to a direct URL
return redirect('/');

return back()->withInput when using a link

I am trying to first post my form to my method that returns a view to preview the post that has been done. When you get to the new view of the preview i want to be able to use a link to go back to the previous page with all form inputs already filled in.
I have tried doing this with setting another url and route to the link where the route triggers a method in my controller with the return back() call. This does not seem to work and i guess it is because it is outside my method with the $request.
So i am wondering how it would be possible to achieve what i want to do. Im using Laravel 5.5
EDIT
Here is my current code:
After the form is posted, you are sent to this method:
public function store(Request $request)
{
$preview = new Preview();
$preview->post_title = $request->title;
$preview->save();
$previewData = Preview::latest('id')->first();
return view('pages.preview_ad')->with('previewData', $previewData);
}
In the 'preview_ad' view, i want to have a link that routes to another method that triggers
return back()->withInput();
Although when i try to do this with the code below, it does not return the previous page with the inputs which the code above should. It works properly if i run it inside the 'store' method above, but not in the other method.
Route::get('/Skapa-annons/Tillbaka', 'PreviewsController#go_back');
-
public function go_back()
{
return back()->withInput();
}

controller/create/id not allowing any data - Laravel

I'm designing a system where I need to create a comment that leaves a comment on a specific user's page.
Currently in my employercommentscontroller I have the create function
public function create($id)
{
$user = User::where('employee_id', $id)->get();
return view('comments.create', compact('user'));
}
Here is the route to this controller file
Route::resource('/reviews', 'EmployerCommentsController');
This is so that I can display information about the user that the comment is being left about. When I go to the url.
When I visit /reviews/create/2, I get a notfoundhttpexception. What do I need to change to be able to pass just the ID to my create method?
You may use:
Route::get('/reviews/create/{id}', 'EmployerCommentsController#create');
For further information: https://laravel.com/docs/5.1/routing
If you don't want to create additional routes and you want to use standard RESTful controller, you can just create link with GET parameter:
Write a comment
And then get this parameter in controller:
public function create()
{
$id = request()->input('id');

Slim with laravel pagination, always page 1

I required Illuminate/pagination into my Slim 3 project
I've the following in my route:
$this->get('/traces', 'UserController:getTraces')->setName('user.traces');
In the getTraces method:
public function getTraces($req, $res)
{
$loginRows = $this->db->table('login_history')->where('user_id', $_SESSION['user'])->orderBy('id', 'desc')->paginate(5);
$loginRows->setPath($this->router->pathFor('user.traces'));
$this->view->getEnvironment()->addGlobal('login_rows', $loginRows);
return $this->view->render($res, 'user/traces.twig');
}
In my view (I'm using Twig):
{{ login_rows.render() | raw }}
So everything is working just fine and also the pagination html links, but even if I go to ?page=2 or any other page. It always display first page 1 with same rows. It says that it detect the page number but obviously it's wrong, is there a way I can set the page number manually or a fix if the problem is actually in my code?
Thanks in advance.
If anyone interested, I just did that:
$loginRows = $this->db->table('login_history')->where('user_id', $_SESSION['user'])->orderBy('id', 'desc')->paginate(5, ['*'], 'page', $req->getParam('page'));
$loginRows->setPath($this->router->pathFor('user.traces'));
This is fixed my problem, I'm sure there is a better solution but at least this works!
The problem is that Eloquent's Paginator doesn't know how to extract the "page" parameter from Slim's router. But you can give it a new function to help. Here I've created a middleware that tells the Paginator how to find the "page" parameter.
<?php
/**
* Tells the Eloquent Paginator how to get the current page
*/
namespace App\Middleware;
class Pagination {
public function __invoke($request, $response, $next)
{
\Illuminate\Pagination\Paginator::currentPageResolver(function() use ($request) {
return $request->getParam('page');
});
return $next($request, $response);
}
}
Then when setting up the app, you can add this:
$app->add(new App\Middleware\Pagination);
Be aware that will be run for every page request (even those without pagination). I doubt it's really a performance hit. If concerned, you can apply it to specific routes. Or call currentPageResolver() just before your query.

Laravel 5 route giving error "This webpage has a redirect loop"

I am using Laravel 5 and have declared a route that corresponds to a controller action but it gives an error of "This webpage has a redirect loop" and net::ERR_TOO_MANY_REDIRECTS in case of ajax calls.
My route is:
Route::get('getsubcategories/{id}', 'HomeController#getsubcategories')
->where('id', '[0-9]+');
Controller:
public function getsubcategories($id){
return "abc";
}
I don't know where the problem resides. Any suggestions ?
If you are using Form Request, make sure you are not injecting the class in the constructor.
My mistake was this:
public function __construct(SupplierFormRequest $supplier)
{
$this->supplier = $supplier;
}
instead of injecting the interface there.

Categories