Preview Link Inside Post Body Laravel - laravel

I planned on embedding URLs into a post body when the post is been created and also would like if the automatically preview details inside the post body after it has been submitted, URLs like YouTube , Twitter, Instagram I would like to automatically display there details inside a post body
please how can I do this?
using this package
https://github.com/oscarotero/Embed
preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $post->body, $urls);

So you need to do this process before passing the post body to the view also specify a section to show your data, like so
Your PHP Code
public function show (Post $post)
{
// Your pattern to find the URL that you want
$isMatch = preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $post->body, 'matches_urls');
$urlDetails = [];
foreach ($urlsThatYouFind as $url)
{
$embed = new Embed();
// Load any url
$info = $embed->get($url);
$urlDetails['info'] = $info;
// Get content info
$urlDetails['title'] = $info->title; //The page title
}
return view('post.view', compact('post', 'urlDetails'));
}
Your view
<p>{{ $post->body }}</p>
<div>{{ $urlDetails['title'] }}</div>

Related

Issue in displaying the data to view page in laravel, but the value is getting passed through url and its not getting displayed in the view page

Find below the controller code, Here I'm getting the data's passed in the url and I need the data entered through the form to be displayed / printed in the view page..
Controller Code:
public function create(Request $request)
{
$domainname = Input::get('domainname');
$tld = Input::get('tld');
$url='https://httpapi.com/api/domains/available.json?auth-userid=711757&api-key=74miSZPgYkkc108Ptmeo5Q8iDTtKk3xi&domain-name=';
$ch = curl_init($url.$domainname.'&tlds='.$tld);
711757&api-key=74miSZPgYkkc108Ptmeo5Q8iDTtKk3xi&domain-name='.$domainname.'&tlds='.$tld.'&suggest-alternative=true');
$result = curl_exec($ch);
$final_data = json_decode($result,true);
dd($final_data);
return view('clientlayout.main.tld',compact('final_data'));
}
tld.blade.php:
{{print_r($final_data)}}
When I use the above code to print the data in view page, it just prints as "11".
Route code:
Route::get('tld','TldController#create')->name('domain.create');
Kindly help me with this to solve the issue and print the data in the view page.
$dataFromForm = $request->FieldNameFromForm
This will allow you to get the data from the form, assuming you use a POST or GET request.
In the form named "greeting":
<html>
<body>
<h1>Hello, {{ $name }}</h1>
</body>
</html>
In controller:
return view('greeting', ['name' => 'James']);

Tracking clicks on Download button and save in database

I have simple Download button which is looks like this
<a download="{{ $thumb }}" href="{{ $thumb }}" class="btn btn-success">Download Image</a>
It is appearing on page when the image is found. The button is working perfectly and is downloading the image.
The page has simple input field which user can search the image and if image is found it's showed on page with button download.
I've made a function which saves each string which is searched and now I'm wondering if I can save also if button Download is clicked e.g. the image is downloaded.
Can someone show me an example? I'm using laravel 5.4 here. So maybe I need to pass to the controller click event?
Current controller function
public function getImage(Request $request)
{
$url = get_curl_content_tx('http://example.com/api?url='.$request->input('url'));
$items = json_decode($url, true);
$thumb = $items['thumbnail_url'];
$db_save = new Image();
$ip = $request->ip();
$ip = DB::connection()->getPdo()->quote($ip);
$db_save->url = $request->input('url');
$db_save->ip = DB::raw("inet_aton($ip)");
$db_save->save();
return view('getImage',compact('thumb'));
}
Yes. Make sure that the href is going to a route where you keep track of these records and you can pass on the specific image to update the Record Model of the Image model itself if the counter is there? Something like this:
public function TrackDownload(Image $image){
$imageRecord = Record::where('image_id', '=', $image->id);
$imageRecord->update([
'download_counter' => $imageRecord->download_counter + 1;
]);
return redirect()->route();
}

how construct route pattern for an unknown number of tags - Laravel & Conner/Taggable

I have a blog and a quotationfamous sayings repository on one site.
The quotations are tagged and the entries are tagged too.
I use this rtconner/laravel-tagging package.
Now, what I want to do is to display ALL Quotation models which share the same tags as article.
The Eloquent syntax is simple, as the original docs provide an example:
Article::withAnyTag(['Gardening','Cooking'])->get();
possible solution
Optional routing parameters. The asker-picked answer in this question gives a solution:
//in routes.php
Route::get('/{book?}/{chapter?}/{topic?}/{article?}', 'controller#func');
//in your controller
public function func($book = null, $chapter = null, $topic = null, $article = null) {
...
}
my problem
In my app the shared tags might count more than 3 or 5. I will soon get an example with even 10 tags. Possibly more
My question
Does it mean that I have to construct an URL with 10 optional routing parameters? Do I really need sth like this:
Route::get('quotations/tags/{tag1?}/{tag2?}/{tag3?}/{tag4?}/{tag5?}/{tag6?}/{tag7?}', 'controller#func');
my question rephrased
I could create a form with only a button visible, and in a hidden select field I could put all the tags. The route would be a POST type then and it would work. But this solution is not URL-based.
I think you could process the slashes, as data:
Route::get('quotations/tags/{tagsData?}', 'controller#func')
->where('tagsData', '(.*)');
Controller:
public function controller($tagsData = null)
{
if($tagsData)
{
//process
}
}
Ok, this is my solution. As I have a tagged model, I dont't need to iterate through tags in url to get the whole list of tags.
The enough is this:
// Routes file:
Route::get('quotations/all-tags-in/{itemtype}/{modelid}', 'QuotationsController#all_tagged_in_model');
Then in my controller:
public function all_tagged_in_topic($itemtype, $id) {
if($itemtype == 'topic') {
$tags = Topic::find($id)->tags->pluck('name')->all();
$topic = Topic::find($id);
}
if($itemtype == 'quotation') {
$tags = Quotation::find($id)->tags->pluck('name')->all();
$quotation = Quotation::find($id);
}
// dd($tags);
$object = Quotation::withAnyTag($tags)->paginate(100);;
And it is done.
Now, the last issue is to show tags in the URL.
TO do that, the URL should have an extra OPTIONAL parameter tags:
// Routes file:
Route::get('quotations/all-tags-in/{itemtype}/{modelid}/{tags?}', 'QuotationsController#all_tagged_in_model');
And in the {url?} part you can just write anything which won't break the pattern accepted by route definition.
In your view you might generate an URL like this:
// A button to show quotes with the same set of tags as the article
// generated by iteration through `$o->tags`
<?php
$manual_slug = 'tag1-tag2-tag3-tag4`;
?>
<a href="{{ URL::to('quotations/all-tags-in/article/'.$o->id.'/'.$manual_slug) }}" class="btn btn-danger btn-sm" target="_blank">
<i class="fa fa-tags icon"></i> Tagi:
</a>

Making object accessible throughout application

I am adding user notifications to my system. To access these notifications for a user, I call an API I have created in another system. So, my IndexController looks something like the following
public function index()
{
if ($user = Sentinel::getUser()) {
$notifications = MyAPI::returnNotifications($user->id);
return view('centaur.dashboard', compact('notifications'));
}
}
Now to problem with the above is that notifications is now only available on the dashboard view. Within my header view I have something like this
#if($notifications)
#foreach($notifications as $notification)
<a class="content" href="#">
<div class="notification-item">
<h4 class="item-title">{{ $notification->subject }}</h4>
<p class="item-info">{{ $notification->body }}</p>
</div>
</a>
#endforeach
#endif
But if I now visit another page besides the dashboard page I get a Undefined variable: notifications error. This is because header is on every page, but I am only passing my notification object to the dashboard page.
Is there any way to make this notification object universally available?
Thanks
UPDATE
if($user = Sentinel::getUser()) {
view()->composer('*', function ($view) {
$view->with('notifications', MyAPI::returnNotifications($user->id));
});
}
You can use a view composer. In your App\Providers\AppServiceProvider#boot method add:
view()->composer('*', function ($view) {
$view->with('notifications', MyAPI::returnNotifications($user->id););
});
Now you'll have the variable $notifications in all of your views. If you want it for specific ones just replace the * with the view name.

How to grab content from section within blade template

I have written a training application with each page/slide of the training workbook as a seperate blade template file named as "page1.blade.php", "page2.blade.php" and so on. Each of these files has content of the kind:
#extends('en/frontend/layouts/training_modulename')
{{-- Page title --}}
#section('title')
Page Title
#parent
#stop
{{-- Page content --}}
#section('pageContent')
<div class="pageContentContainer">
<h2>Page Title</h2>
...
</div>
#stop
This works really well when being viewed page by page within the browser. However I also wish to automatically compile all pages into a PDF document. This is being done via dompdf which works amazingly well when I pass each pages html to it manually. However I wish to condense the #section('pageContent') section of each page into one large section which extends a different layout for passing to dompdf.
Given the above context my question is this:
Is there a method in Laravel's blade parser which would allow me to pass it a blade file and just get the rendered html from a particular section? The below pseudo-code demonstrates what I would like to be able to do.
$pages = array(...); // content of the directory
foreach ($pages as $page)
{
$renderedPage = Blade::render($page);
$title = $renderedPage->title;
$pageContent = $renderedPage->pageContent;
}
Instead of doing the normal return of view
return View::make('page');
You can instead store the view in a string
$view = View::make('page');
So then you can do your code something like this (not tested - but you get the idea):
$pages = array(...); // content of the directory
foreach ($pages as $page)
{
$renderedPage[] = view::make($page);
}

Resources