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

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('/');

Related

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();
}

Setting session variables in Laravel 5.4

I have a feeling this is a very dumb question and there's probably something really tiny I just overlooked, but I'm stumped anyway.
Currently, I have an app with a few pages that are protected through middleware. If the user does not meet the requirements of these middleware, they are redirected to a login page. Now after they log in, I want them to be sent back to the page they tried to visit.
I've tried numerous things to accomplish this, but none work. What I'm trying to do now is the following:
User attempts to access an admin page (for example /admin): PagesController#adminDashboard
When they access the overview() method in the controller (same as index(), but for admins), a session variable is set containing the url they tried to visit (/admin)
The user is redirected to the login page and logs in (SessionsController#create and #store)
After logging in, they are redirected to the session variable with the intended URL
This is how I tried to do it:
PagesController
public function adminDashboard()
{
$intended = '/admin';
session('intended-url', $intended);
//dd(session('intended-url');
$schools = School::all();
$articles = Article::all();
$sights = Sight::all();
return view('admin', compact('sights', 'articles', 'schools'));
}
SessionsController
public function store()
{
/*
...
*/
$intendedURL = session('intended-url');
if($intendedURL != null)
{
return redirect($intendedURL);
}
else
{
return redirect()->home();
}
Using dd() a few times here and there, I found out that it doesn't even set the session variable at the very start (commented dd() in PagesController returns null).
I've tried doing this using Session::put(), Session::set(), using square brackets as in session(['intended-url', '/admin']), but none of it gives me the result I'm looking for :(
Does anyone have any advice on how to do this, or perhaps a different way of accomplishing the same goal, but more efficiently? Thank you!
EDIT: I don't think the default Laravel redirect to intended page will work here, since I rewrote most of the login system from scratch to suit some specific needs. Unless anyone knows how that redirect works behind the scenes and I can over-/rewrite it
If you are using the default auth system, you can use this to redirect users to the page they wanted to view:
return redirect()->intended('fallback/uri');
why u are not using middleware just make new middleware
php artisan make:middleware admin
and add this code of public function handle
if (!Auth::guest() && Auth::user()->admin) {
return $next($request);
}
return redirect('/')->with('warning', 'This Area only For Admin');
add this code in kernal on protected $routeMiddleware
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\admin::class,
];
make new column in users table
$table->boolean('admin')->default(false);
now you can use your construct function
public function __construct()
{
$this->middleware('admin');
}
Note:- where u add $this->middleware('admin'); all controller will be locked for users and guest only admin can use this controller

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');

Pass value from one view to other laravel routes configuration

I have just started using laravel and currently using the version 5.2.
I am using two forms to get the data. First form in first view and second form in second view. I need to figure out a way to tell the second form, the form id of the first one, which the second form will be linked to.
I know this can be done by passing the values using the URL. But I lack the knowledge of the correct syntax.
1- How to send data while redirecting?
2- How should the route look like?
3- How to access that value in the second view, in order to pass that value when the second form submits?
I have googled a lot about this but couldn't understand those advanced syntax.
Any help is appreciated.
Thanks in advance.
This is the code in controller:
public function postCreateProfile(Request $request){
//Adding attributes from $request to $profile
$profile->save();
Session::flash('values',$request->azauj_id);
return redirect('/add/requirement');
}
public function getCreateRequirement(Request $request){
$att = Session::get('value');
Session::flash('value',$att);
return view('req');
}
public function postCreateRequirement(Request $request){
dd(Session::get('value'));
}
The forms are plain html forms with post methods of submission
When I use dd(Session::get('value'));, i get null. It means that the value is not being passed. To the postCreateRequirement method which is called when the second form is submitted.
Below are the routes.
//For Add Profile Page
Route::get('/add', 'ProfileController#getCreateProfile');
//For Add Profile Form Submission
Route::post('/add', 'ProfileController#postCreateProfile');
//For Add Requirements Page
Route::get('/add/requirement', 'ProfileController#getCreateRequirement');
//For Add Requirements Form Submission
Route::post('/add/requirement', 'ProfileController#postCreateRequirement');
1- How to send data while redirecting?
You can simply pass data with your redirect using the ->with() method which creates an session that will only appear on the next page more here
Example:
Say you want to send a status down to your view you add the with to your redirect:
// Where you are redirecting to
redirect("/otherRoute")->with("status", "Profile updated!");
// session name // data
Now you simply check if the session exist and echo it out:
// If the session does not exist it will return false and not create it
#if (session("status"))
<div class="alert alert-success">
// echo out the session
{{ session("status") }}
</div>
#endif
2- How should the route look like?
Routes should be defined in the routes.php file located in the http directory assuming you are posting the data you should make the routes and connect them to your controller like so:
//For Add Profile Page
Route::get('/add', 'ProfileController#getCreateProfile');
//For Add Profile Form Submission
Route::post('/add', 'ProfileController#postCreateProfile');
//For Add Requirements Page
Route::get('/add/requirement', 'ProfileController#getCreateRequirement');
//For Add Requirements Form Submission
Route::post('/add/requirement', 'ProfileController#postCreateRequirement');
3- How to access that value in the second view, in order to pass that value when the second form submits?
You could simply use the ->with() method in your redirect
public function postCreateProfile(Request $request){
//Adding attributes from $request to $profile
$profile->save();
return redirect('/add/requirement')->with("value",$request->azauj_id);
}
Get the value
public function getCreateRequirement(Request $request){
$value = session("value");
// compact it and trow it in an input to pass it trough to the last controller method
return view('req');
}
public function postCreateRequirement(Request $request){
$request->get("value");
}
OR
Create a global session and flush it afterwards
public function postCreateProfile(Request $request){
//Adding attributes from $request to $profile
$profile->save();
session("value",$request->azauj_id);
return redirect('/add/requirement');
}
Get the value
public function getCreateRequirement(Request $request){
return view('req');
}
public function postCreateRequirement(Request $request){
$value = session("value");
$request->session()->forget("value");
}
Note: Laravel does not flush sessions when somone logs out these will remain if not flushed by hand or using the method $request->session()->flush();

pass user information in every function of the controller in laravel

I have a Controller witch contains more than 150 functions. almost all of the functions inside the controller are returning views.
each view should change if the user is logged in.
I almost handled this in the view side by using parent blades and etc. But in the controller side for almost every function i should check if the user is logged in and return some specific data about the user along with the view.
for example:
$user=[];
if(Auth::check())
{
$user=Auth::user;
$reputation=$user['reputation'];
$messages=$user->messages();
$notifications=$user->notification();
}
return view('pages.profile')->with(['user'=>$user , 'messages'=>$messages , 'notifications'=>$notifications]);
I thought that this is possible using middlewares but i could not figure it out.
what are the alternatives here?
for more information i am using laravel 5.
One solution could be using your custom function instead of view(). Sth like:
//in your controller action
public function someAction() {
return $this->view('pages.profile');
}
protected function view($template, $data = array()) {
return view($template)->with($data)->with([data that needs to be passed to all views]);
}

Categories