Lumen Blade result to array gives empty value - laravel

When I put the following code in my controller in Lumen it returns an empty value for the 'info' key, which should contain the Blade template:
$return = array();
$return['cities'] = $cities;
$return['info'] = view('popup/dialog')->with('result',$result);
return $return;
This returns the following
{"cities":["Den Helder"],"info":{}}
But when I only return the 'info' value, it will show the Blade template
return $return['info'];
I'm using this implementation in an websocket environment. I want to keep the websocket calls to a minimum. So it would be great to return the contents of the template, within the dataset.
Hope you can help.
Offtopic: I'm reading for a couple of years on this site, but this is my first post. If I'm doing something wrong, please tell me.
Thanks in advance!

You need to use the render() method to generate the HTML content of you view.
This should work:
$return['info'] = view('popup/dialog')->with('result',$result)->render();
http://laravel.com/api/5.0/Illuminate/View/View.html#method_render

Related

Passing data from blade to blade in Laravel

I have a page where you can create your workout plan. Second page contains "pre-saved" workouts and I want them to load by passing parameters from second page to first. If you directly access first page, you create your workout plan from scratch.
// first page = https://prnt.sc/y4q77z
// second page = https://prnt.sc/y4qfem ; where you can check which one you want to pass to first page
// final step looks like this: https://prnt.sc/y4qh2q - but my URL looks like this:
www.example.com/training/plan?sabloni%5B%5D=84&sabloni%5B%5D=85&sabloni%5B%5D=86
this 84,85,86 are IDS
Can I pass params without changing URL ? Like having only /training/plan without anything after ?
public function plan(Request $request){
$workout = false;
if($request->workout){
$workout = $request->workout;
$workout = SablonTrening::find($sabloni); // $workout = array [1,3,4,5,6]
}
return view('trener.dodaj_trening', compact('workout'));
}
If you are getting to the /training/plan page with GET request, you could simply change it to POST. That way the parameters would be hidden in the URL but would be present in the request body. You would need a new post route:
Route::post('/training/plan', 'YourController#plan')->name('training.plan');
And then, in the form where you are selecting these plans, change the method on submit:
<form action="{{route('training.plan')}}">
//Your inputs
</form>
Your method should still work if your inputs stay the same.
Note: Not sure you would still keep the functionalities that you need, since I can't see all the logic you have.
If you have any questions, let me know.
To pass data from on blade to another blade.
At the end of first post before redirect()-route('myroute') add $request->session()->put('data', $mydata);
At the begining of the route 'myroute', just get back your data with $data = $request->old('data');

Get last part of current URL in Laravel 5 using Blade

How to get the last part of the current URL without the / sign, dynamically?
For example:
In www.news.com/foo/bar get bar.
In www.news.com/foo/bar/fun get fun.
Where to put the function or how to implement this in the current view?
Of course there is always the Laravel way:
request()->segment(count(request()->segments()))
You can use Laravel's helper function last. Like so:
last(request()->segments())
This is how I did it:
{{ collect(request()->segments())->last() }}
Use basename() along with Request::path().
basename(request()->path())
You should be able to call that from anywhere in your code since request() is a global helper function in Laravel and basename() is a standard PHP function which is also available globally.
The Route object is the source of the information you want. There are a few ways that you can get the information and most of them involve passing something to your view. I strongly suggest not doing the work within the blade as this is what controller actions are for.
Passing a value to the blade
The easiest way is to make the last part of the route a parameter and pass that value to the view.
// app/Http/routes.php
Route::get('/test/{uri_tail}', function ($uri_tail) {
return view('example')->with('uri_tail', $uri_tail);
});
// resources/views/example.blade.php
The last part of the route URI is <b>{{ $uri_tail }}</b>.
Avoiding route parameters requires a little more work.
// app/Http/routes.php
Route::get('/test/uri-tail', function (Illuminate\Http\Request $request) {
$route = $request->route();
$uri_path = $route->getPath();
$uri_parts = explode('/', $uri_path);
$uri_tail = end($uri_parts);
return view('example2')->with('uri_tail', $uri_tail);
});
// resources/views/example2.blade.php
The last part of the route URI is <b>{{ $uri_tail }}</b>.
Doing it all in the blade using the request helper.
// app/Http/routes.php
Route::get('/test/uri-tail', function () {
return view('example3');
});
// resources/views/example3.blade.php
The last part of the route URI is <b>{{ array_slice(explode('/', request()->route()->getPath()), -1, 1) }}</b>.
Try request()->segment($number) it should give you a segment of the URL.
In your example, it should probably be request()->segment(2) or request()->segment(3) based on the number of segments the URL has.
YourControllor:
use Illuminate\Support\Facades\URL;
file.blade.php:
echo basename(URL::current());
It was useful for me:
request()->path()
from www.test.site/news
get -> news
I just had the same question. In the meantime Laravel 8. I have summarised all the possibilities I know.
You can test it in your web route:
http(s)://127.0.0.1:8000/bar/foo || baz
http(s)://127.0.0.1:8000/bar/bar1/foo || baz
Route::get('/foo/{lastPart}', function(\Illuminate\Http\Request $request, $lastPart) {
dd(
[
'q' => request()->segment(count(request()->segments())),
'b' => collect(request()->segments())->last(),
'c' => basename(request()->path()),
'd' => substr( strrchr(request()->path(), '/'), 1),
'e' => $lastPart,
]
)->where('lastPart', 'foo,baz'); // the condition is only to limit
I prefer the variant e).
As #Qevo had already written in his answer. You simply make the last part part of the request. To narrow it down you can put the WHERE condition at the route.
Try with:
{{ array_pop(explode('/',$_SERVER['REQUEST_URI'])) }}
It should work well.

How to automatically append query string to laravel pagination links?

I am working on search filter on checkbox click, with Laravel and Ajax call. So I get results when I click on a checkbox. my query is as follows:
$editors = User::with(['editor.credentials','editor.specialties','editor.ratings']);
$temp=$editors->whereHas('editor', function($q) use ($a_data){
$q->whereHas('specialties',function($sq) use($a_data){
$sq->whereIn('specialty',$a_data);
});
})->paginate(2);
This gives me all the data I need. however how should I get the links for pagination?
$temp->setBaseUrl('editors');
$links = $temp->links()->render();
I am currently doing this and with $links which I am sending over as response to ajax call, I set the pagination with $links data. Now, I need to append the query to next page like page=2?query="something". I don't know how should I go about appending the remaining query result links to next page links. i.e. I don;t know what should come in the query="something" part. Can someone guide me. thanks
{{ $users->appends($_GET)->links() }}
It will append all query string parameters into pagination link
As of Laravel 7, you can call the withQueryString() method on your Paginator instance.
Quote from the documentation:
If you wish to append all current query string values to the pagination links you may use the withQueryString method:
{{ $users->withQueryString()->links() }}
See "Appending To Pagination Links": https://laravel.com/docs/7.x/pagination#displaying-pagination-results
Check the answer from #Arda, as it's global solution. Below you can find how to do it manually.
Use appends on Paginator:
$querystringArray = Input::only(['search','filter','order']); // sensible examples
// or:
$querystringArray = ['queryVar' => 'something', 'anotherVar' => 'something_else'];
$temp->appends($querystringArray);
Append all input except the actual page, form token and what you don't want to pass:
$paginatedCollection->appends($request->except(['page','_token']));
For the latest version of Laravel at the moment (5.2), you can just use the Request facade to retrieve the query string and pass that to your paginator's appends() method
$input = Request::input();
$myModelsPaginator = App\Models\MyModel::paginate();
$myModelsPaginator->appends($input);
Add this anywhere in your app (e.g routes.php, filters.php or anything that's autoloaded), no need to edit any pagination codes that is written already. This works flawlessly using view composers, and you don't need to know any query string parameters:
////////PAGINATION QUERY STRING APPEND
View::composer(Paginator::getViewName(), function($view) {
$queryString = array_except(Input::query(), Paginator::getPageName());
$view->paginator->appends($queryString);
});
//////////////////
Inspired from previous answers I ended up using the service container for both frontend + api support.
In your AppServiceProvider#boot() method:
$this->app->resolving(LengthAwarePaginator::class, function ($paginator) {
return $paginator->appends(array_except(Input::query(), $paginator->getPageName()));
});
you can used request helper in view as same
{{ $users->appends(request()->query())->links() }}
in your view where you display pagination...
{{ $results->appends(Request::except('page'))->links() }}
appends keeps the query string value except "page". not sure if it will work with POST request
{{ $users->appends(Request::only(['filter','search']))->links()}}
Updating #rasmus answer for Laravel 8.
In your AppServiceProvider boot method, add the following lines and your existing query string will be be used for all pagination links
$this->app->resolving(Paginator::class, function ($paginator) {
return $paginator->appends(Arr::except(Request::query(), $paginator->getPageName()));
});
$this->app->resolving(LengthAwarePaginator::class, function ($paginator) {
return $paginator->appends(Arr::except(Request::query(), $paginator->getPageName()));
});
And for completeness, use these classes:
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Request;

Laravel Trying to get property of non-object but not sure why

I want to grab some data from a database and display on a layout page, I've basically started building a small CMS to get into Laravel and all has gone fine so far but now i'm at a wall, and can't find a solution.
I have a layout blade file like so: http://paste.laravel.com/1fB1 nothing majot but you will see i have used $page->meta_title etc in there and in my controller i have:
public function home()
{
$pages = Pages::all();
return View::make('frontend/home')->with('pages',$pages);
}
Which I have a pages model doing nothing else really like so:
class Pages extends Eloquent {
protected $table = 'pages';
}
So why is it trying to get property of non-object and I don't really want to use a foreach because this is going to be the frontend of my 'test' website so a foreach wouldn't suite.
You'll need to access these items as a multi-dimensional array if you don't want to loop through them.
$pages[0]['field_name_here']
or
$pages[1]['field_name_here']
Its a bit of a tough one to answer without knowing how you want your CMS to work.
For example, you could have a route as {pagename} in your routes.php file, then have a page controller where you would get the requested route from the variable passed in. This would then load the page you wanted using the variable
public function page( $pagename ) {
$page = Page::where('page_title', '=', $pagename)->first();
View::make('frontend/page', array( 'page' => $page ));
}
Using a route like that, and the controller, in your view you could use {{ $page->content }} to get the content of the requested page from the database and display it.
Hope this helps.
Edit: Example Route:
Route::get('{pagename}', 'PageController#page');

CodeIgniter - Dynamic URL segments

I was wondering if someone could help me out.
Im building a forum into my codeigniter application and im having a little trouble figuring out how i build the segments.
As per the CI userguide the uri is built as follows
www.application.com/CLASS/METHOD/ARGUMENTS
This is fine except i need to structure that part a bit different.
In my forum i have categories and posts, so to view a category the following url is used
www.application.com/forums
This is fine as its the class name, but i want to have the next segment dynamic, for instance if i have a category called 'mycategory' and a post by the name of 'this-is-my-first-post', then the structure SHOULD be
www.application.com/forums/mycategory/this-is-my-first-post
I cant seem to achieve that because as per the documentation the 'mycategory' needs to be a method, even if i was to do something like /forums/category/mycategory/this-is-my-first-post it still gets confusing.
If anyone has ever done something like this before, could they shed a little light on it for me please, im quite stuck on this.
Cheers,
Nothing is confusing in the document but you are a little bit confused. Let me give you some suggestions.
You create a view where you create hyperlinks to be clicked and in the hyperlink you provide this instruction
First Post
In the controller you can easily get this
$category = $this->uri->segment(3);
$post = $this->uri->segment(4);
And now you can proceed.
If you think your requirements are something else you can use a hack i have created a method for this which dynamically assign segments.
Go to system/core/uri.php and add this method
function assing_segment($n,$num)
{
$this->segments[$n] = $num;
return $this->segments[$n];
}
How to use
$this->uri->assign_segment(3,'mycategory');
$this->uri->assign_segment(4,'this-is-my-first-post');
And if you have error 'The uri you submitted has disallowed characters' then go to application/config/config.php and add - to this
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
You could make a route that forwards to a lookup function.
For example in your routes.php add a line something like;
$route['product/(:any)/(:any)'] = "forums/cat_lookup/$1/$2";
This function would then do a database lookup to find the category.
...
public function cat_lookup($cat, $post) {
$catid = $this->forum_model->get_by_name($cat);
if ($catid == FALSE) {
redirect('/home');
}
$post_id = $this->post_model->get_by_name($post);
/* whatever else you want */
// then call the function you want or load the view
$this->load->view('show_post');
}
...
This method will keep the url looking as you want and handle any problems if the category does not exist.Don't forget you can store the category/posts in your database using underscores and use the uri_title() function to make them pretty,
Set in within config/routes.php
$route['song-album/(:any)/:num'] = 'Home/song_album/$id';
fetch in function with help of uri segment.
$this->uri->segment(1);

Resources