How to access URL segment(s) in blade in Laravel 5? - php

I have a url : http://localhost:8888/projects/oop/2
I want to access the first segment --> projects
I've tried
<?php echo $segment1 = Request::segment(1); ?>
I see nothing print out in my view when I refresh my page.
Any helps / suggestions will be much appreciated

Try this
{{ Request::segment(1) }}

BASED ON LARAVEL 5.7 & ABOVE
To get all segments of current URL:
$current_uri = request()->segments();
To get segment posts from http://example.com/users/posts/latest/
NOTE: Segments are an array that starts at index 0. The first element of array starts after the TLD part of the url. So in the above url, segment(0) will be users and segment(1) will be posts.
//get segment 0
$segment_users = request()->segment(0); //returns 'users'
//get segment 1
$segment_posts = request()->segment(1); //returns 'posts'
You may have noted that the segment method only works with the current URL ( url()->current() ). So I designed a method to work with previous URL too by cloning the segment() method:
public function index()
{
$prev_uri_segments = $this->prev_segments(url()->previous());
}
/**
* Get all of the segments for the previous uri.
*
* #return array
*/
public function prev_segments($uri)
{
$segments = explode('/', str_replace(''.url('').'', '', $uri));
return array_values(array_filter($segments, function ($value) {
return $value !== '';
}));
}

The double curly brackets are processed via Blade -- not just plain PHP. This syntax basically echos the calculated value.
{{ Request::segment(1) }}

Here is how one can do it via the global request helper function.
{{ request()->segment(1) }}
Note: request() returns the object of the Request class.

An easy way to get the first or last segment, in case you are unsure of the path length.
$segments = request()->segments();
$last = end($segments);
$first = reset($segments);

Here is code you can get url segment.
{{ Request::segment(1) }}
If you don't want the data to be escaped then use {!! !!} else use {{ }}.
{!! Request::segment(1) !!}
https://laravel.com/docs/4.2/requests

Related

Laravel, only first element of array passed to route is readable

From a blade template I want to pass an array with a variable amount of values to a route, as described in the answer here.
However when I do this I can only ever access the first value in the array I pass to the route.
This is how I call the route in the blade template:
{{ route('stats.downloads', ['stat_kind' => 'files_size', 'group_by' => 'week', 'start' => '2020-11-01', 'end' => '2020-11-10']) }}
this is my route from web.php:
Route::get('stats/downloads', 'StatsController#view_stats_downloads')->name('stats.downloads');
and my controller:
public function view_stats_downloads(Request $request){
// get the input parameters
$group_by = $request->get('group_by');
$stat_kind = $request->get('stat_kind');
$company = $request->get('group_by');
$user = $request->get('user');
$start = $request->get('start');
$end = $request->get('end');
...
The problem is, that I can only ever access the first value of the array I pass to the controller (stat_kind in this case). It doesn't natter in which order I call the get() function either.
What can I do to fix this?
I'm running laravel 5
Try changing the curly braces, {{ }}, to {!! !!} where you are calling the route helper.
The & is being encoded to & so only the first query string parameter that you are sending does not have a & in front of it so it is named correctly. The others are named with the amp;, the part after the & in the encoded ampersand.

Redirect back to form with data in laravel

I have this function in the controller.
public function newsedit($id)
{
$editNews = $this->agro->find($id);
//return $editNews;
return Redirect::back()->with('editNews',$editNews);
//return View::make('agro.show')->with('editNews',$editNews);
}
The return $editNews displays data, so there is data in $editNews.Now i am trying to pass the same data to the view using redirect as shown in the above code.
But apparently the value is not passed. The following code shows the value is not availabel in the view
#if(isset($editNews))
<h1> value availabel</h1>
#else
<h1> No value </h1>
#endif
It displays No value . Please help me pass the data to view.I don't understant where have i gone wrong.
Laravel 4:
#if(Session::has('editNews'))
Laravel 5:
#if(session()->has('editNews'))
If you want to get the data, replace has() with get()
return View::make('agro.show', ['editNews' => $editNews]);
You can simply use
#if( Session::get( 'editNews' ) )
// show something
#endif
in Laravel 4 - it will return false to the #if block if the variable is not set

Changing the {{ URL::to('home'); }} in laravel

Here is my urlto in laravel
{{ URL::to('forgot'); }}
It will point as mysite.com/forgot
How can i insert the value here
i.e.,
$value = '1';
{{ URL::to('forgot'); }}
And it should point mysite.com/1/forgot
How can i insert the value of $value before the forgot
You should concatenate your $value before your url
i.e.,
$value = '1';
{{ URL::to($value.'/forgot/'); }}
You can use named routes with parameters.
Example route:
Route::get('{value}/forgot', array('as' => 'forgot', function($value = null)
{
return "My value: " . $value;
}));
Now building your URL:
{{ route('forgot', 1); }}
You need to use like this check the documentation Documentation Here
$value = '1';
{{ URL::to($value.'/forgot'); }}
one way is to add a variable to your route
an example here my route is
Route::get('/user/{id}'
then at the destination if i call $id, i get the value that was entered in id.
so if i put /user/1 , $id =1.
this can be a issue however if there is nothing. you need to include code to handle if the $id has no value. another way to do it is
return View::make('searchresults', compact('challenges', 'ideas','users'));
here i have sent arrays with search results, and on the page searchresults if i call $ideas i get that array, this will also work with strings i believe.

Twig get url parameter with []

I have an url like : MYURL?filter[_per_page]=25&filter[name][value]=hello
How can i get these parameters with twig ?
I'm trying {{ app.request.get('filter[_per_page]') }} but it's always empty...
Thanks !
Edit : I'm in javascript an i want to assign this result to a javascript variable like : var param = "{{ app.request.get('filter[_per_page]') }}";
You must manage as an array accessing to the filter element as:
{{ app.request.get('filter')['_per_page'] }}
(This time I try before posting...)
You've almost got it.
app object is GlobalVariables instance. When you say app.request, getRequest() is being invoked and returns an instance of standard Request object.
Now if you look at Request::get() (link) there is:
get(string $key, mixed $default = null, bool $deep = false)
I think what you need to do is this:
{{ app.request.get('filter[_per_page]', NULL, true) }}
Where NULL is default value and true means deep traversal of Request object.
I found a solution like this :
app.request.attributes.get('request').query.get('param_name')
To access to array of query params you can use:
app.request.attributes.get('_route_params');
You can see different solutions on the documentation.

Empty search results Laravel 4

I am making a simple search engine in which, If the selected list from the dropdown would match with the one inside the 'destinationto' column from the database then it would fetch all the items inside that row. But when I hit the find button, it would not return any item from the database. It would be giving me an empty array.
object(Illuminate\Database\Eloquent\Collection)[141]
protected 'items' =>
array (size=0)
empty
What have I done wrong?
Here are the snippets
OnewayflightControllers.php:
public function onewayflightresults()
{
$destinationto = Input::get('destinationto');
$results = Oneways::where('destinationto','=',$destinationto)->get();
var_dump($results);
}
public function onewayflight()
{
$onewaysfrom = DB::table('oneways')->distinct()->lists('destinationfrom');
$onewaysto = DB::table('oneways')->distinct()->lists('destinationto');
return View::make('content.onewayflight')->with(['destinationfrom'=>$onewaysfrom,'destinationto'=>$onewaysto]);
}
onewayflight.blade.php:
{{ Form::label('destinationto','To: ') }}
{{ Form::select('destinationto', $destinationto)}}
It's only a guess but you should make sure you have only one form element with name destinationto
If you have in form for example
{{ Form::label('destinationto','From: ') }}
{{ Form::select('destinationto', $destinationfrom)}}
{{ Form::label('destinationto','To: ') }}
{{ Form::select('destinationto', $destinationto)}}
If you think it's ok, you should add var_dump($destinationto); to your function to make sure value is what you expect
EDIT
I thought select will use values as keys but it's not so you should probably do something like that:
$onewaysfrom = DB::table('oneways')->distinct()->lists('destinationfrom','destinationfrom');
$onewaysto = DB::table('oneways')->distinct()->lists('destinationto','destinationto');
and not:
$onewaysfrom = DB::table('oneways')->distinct()->lists('destinationfrom');
$onewaysto = DB::table('oneways')->distinct()->lists('destinationto');

Categories