Inertiajs - Laravel: Avoid Scroll after Post and Set Header - php

On my index page I have made a chatbox. There I have a form element in my Vue component which executes an inertia post via "UseForm".
The problem I have is, because I make the post on "/chatbox/send", that I have to make a redirect to "index/home" afterwards, because otherwise the URL-header remains "/chatbox/send", which I don't want.
In addition, the page automatically scrolls up again when rendering.
My question; How can I re-render the page so that the URL-header is set to "/home" again and the page does not scroll up ?
public function sendChatMessage(Request $request) {
$msg = $request->input('text');
$username = Auth::user()->only('name')['name'];
if($this->createChatMessage($msg, $username)) {
return redirect('index/home');
}
return false;
}

you have to define it during your route in your vuejs I suppose you use.
Normally it should look like this:
this.$inertia.post(route('chatbox.send'), {text: this.text}, { preserveState: false, preserveScroll: true })
preserveState: it is used to say if you want to refresh the page if you return the same route in your php controller.
preserveScroll: is used to say that you want to stay at the same scrolling as at the time of the send.
more information: https://inertiajs.com/manual-visits
And in your controller I would do:
public function sendChatMessage(Request $request) {
$msg = $request->input('text');
$username = Auth::user()->only('name')['name'];
if($this->createChatMessage($msg, $username)) {
return redirect()->route('home');
}
}

Related

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 to determine if a session with same variable is already there in laravel

I am using Laravel framework. There is a function in controller that creates session with name store_id
StoreController.php
function initiate($id)
{
//Some queries
session['store_id' => 'some value'];
}
Now if I run this function on one tab then session::get('store_id') is going on. But if I open another tab in the same browser then again run the function that means session('store_id') will be again set. How do I handle this situation that if there is already a session then it should redirect to it's perspective url.
Okay first of all, Bruuuhhhh been there and done that
Alright, lets begin. you want that if there is already a session with store_id going on then you want user to redirect or send back.
In your controller add this
public function initiate()
{
if(session()->has('store_id'))
{
//What ever your logic
}
else
{
redirect()->to('/store')->withErrors(['check' => "You have session activated for here!."]);
}
}
Most probably you would be wondering that user can just go to other url after /store/other-urls Yess he can.
To avoid this. Add a custom middleware
php artisan make:middleware SessionOfStore //You can name it anything.
In that middleware
public function handle($request, Closure $next)
{
if($request->session()->has('store_id'))
{
return $next($request);
}
else
{
return redirect()->back()->withErrors(['privilege_check' => "You are not privileged to go there!."]);
}
return '/home';
}
in your main store page. Add an anchor tag Stop Service
Now in your web.php
Route::group(['middleware' => 'SessionOfStore'], function()
{
//Add your routes here.
Route::get('/stop', 'StoreController#flushSession');
});
Now you have restrict access to urls and has checked the sessions.
Now in
public function flushSession()
{
//empty out the session and
return redirect()->to('/home');
}
The Laravel session helper has the function has to check this.
if (session()->has('store_id'))
{
// Redirect to the store
}
else
{
// Set the store id
}
The documentation contains all of the possible functions that can be used with the session helper.

How to redirect different page from same controller function in laravel 5.2

I want to redirect 2 different page from this controller function along with value.Here is my code. It works but both of time url become same.what shuld I do?
//in routes.php
Route::post('/','mycontroller#check');
// in controller.php
public function check(Request $request)
{
$c_email = $request->email;
$c_pass=$request->pass;
$c_type=$request->select;
$var=DB::select("SELECT * FROM reg where email = '$c_email' and Password = '$c_pass' and type = '$c_type'");
if ($var) {
return view('farmer')->with('user',$var);
// return redirect('farmer')->with('user',$var);
}
else {
$msg="Invalid login";
return view('index')->with('show',$msg);
}
}
If you want to actually redirect u can use the redirect() helper as statet in the official docs https://laravel.com/docs/5.3/redirects
You can also pass data
redirect('/my-route')->with(['user' => $var]);
The passed data can then be accesses through the session helper
$var = session('user')
HOWEVER, it seems like you have major issues in your code. Your password does not seem to be encrypted. Also there's no reason to use plain sql instead of eloquent here.
The route that is shown in the browser is defined in your
Route::post('/','mycontroller#check');
If you just return different views, the route does not change. You need to redirect to other views.
If you redirect to other routes you will ofcourse need to add / define them.
Route::get('/my-route', function() {}); // or post etc.

Laravel Redirect to Previous after login

I have a login form and after the form submission (if validation is OK) the browser should redirect to the last page before login. Currently I redirect back and I get always into the same login page.
My routes.php is something like this:
Route::get('/', 'HomeController#index');
Route::get('/list','EventController#index');
Route::get('/login','AuthController#login');
Route::post('/login','AuthController#do_login');
And my Redirection inside do_login() is
if(Login_is_valid())
{
return Redirect::back();
}
If I'm inside /list page and then open Login and fill the form correctly I'm redirected to /login again isn't it weird? Many thanks
Hello if you use Laravel 5.1 you can redirect to previous page next way
return back();
or you can use Session where Laravel save previous page
return redirect(Session::get('_previous')['url']);
in Auth/LoginController there is protected $redirectTo = '/home'; change '/home' to '/loginin' for example, and create a new route that look like this
Route::get('/loginin', function ()
{
$page = '/' . session()->get('page');
if($page != '')
{
session()->put('page', '');
return redirect($page);
}
else
{
return redirect('/home');
}
});
or you can put this in an controller and call it from the route
and in each function in the pages controller this code
session->put('page','/name_of_the_page');

laravel 4.1 validate url input

Okay after get almost every thing work in my code
and its pretty Good
i need help about how to validate the user url Input
and if he did insert a non Url how to foreword it to 404 page
and here is my Route file
Route::get('/', function()
{
return View::make('hello');
});
Route::post('/', function()
{
$url = Input::get('url');
$record = Url::where('urls', '=', $url)->first();
if ($record) {
return View::make('result')
->with('shortend', $record->shortend);
}
function get_uniqe_short_url()
{
$shortend = base_convert(rand(1000,99999), 10, 36);
if (Url::where('shortend', '=' ,$shortend)->first() ){
get_uniqe_short_url();
}
return $shortend;
}
$shortend = get_uniqe_short_url();
// otherwise add new row and return shortned url
$row = new URl;
$row->urls = $url;
$row->shortend = $shortend;
$row->save();
// create a results view and present the short url to the usr
if ($row){
return View::make('result')->with('shortend',$shortend);
}
});
Route::get('{shortend}', function($shortend)
{
// query the DB For the row with that short url
$row = Url::where('shortend', '=', $shortend)->first();
// if not found redirect to home page
if (is_null($row) ) return Redirect::to('/');
// else grab the url and redirect
return Redirect::to($row->urls);
});
forgive me for my many questions but i am totally new to laravel
First, as a tip, you have logic like this in your routes.php. A URL router is meant to take HTTP requests and "route" them to the correct controllers and methods. See the documentation to get started with controllers.
I am never a fan of "redirecting to a 404 page", instead I believe if a page isn't found it should display a 404 page there. To do this with laravel, you can call App::abort(404); which will kill the application and return a 404 status to the browser. You can take this a step further by "listening" to 404 errors and returning your own custom view:
App::missing(function()
{
return View::make('errors/404');
});
Let me know if you need more help validating a URL, but I think you should start by restructuring your code by using controllers. You can check this question for regular expressions to match URLs. This is how you would use a regular expression in PHP:
if(!preg_match('/expression/', $url)) {
App::abort(404);
}

Categories