Undefined variable in Laravel trying to post source ID route - php

Currently Working on building out a news api behind a dashboard. I have just recently started getting the error Undefined variable: sourceId (View: C:\Laravel8Auth\resources\views\dashboard.blade.php).
Ive gone everywhere that has source Id and I cant see to figure out what it could be.
Here are some of the codes necessary, im using Laravel 8.x with JetStream Im fairly new at this just wanted to mess around.
web php
`<?php
use Illuminate\Support\Facades\Route;
use App\Models\Api;
use App\Http\Controllers\ApiController;
///Route::get('/', [ApiController::class,'displayNews']);
///Route::get('/fetchNewsFromSource', [ApiController::class, 'fetchNewsFromSource'])->name('fetchNewsFromSource');
///Route::post('/sourceId', 'ApiController#displayNews');
Route::get('/', 'App\Http\Controllers\ApiController#displayNews');
Route::post('sourceId', 'App\Http\Controllers\ApiController#displayNews');
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
`
Dashboard php
<!DOCTYPE html>
<html lang="{{ config('app.locale') }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>News Application with Laravel</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet" type="text/css">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="appendDivNews">
<nav class="navbar fixed-top navbar-light bg-faded" style="background-color: #e3f2fd;">
<a class="navbar-brand" href="#">News Around the World</a>
</nav>
{{ csrf_field() }}
<section id="content" class="section-dropdown">
<p class="select-header"> Select a news source: </p>
<label class="select">
<select name="news_sources" id="news_sources">
<option value="{{$sourceId}} : {{$sourceName}}">{{$sourceName}}</option>
#foreach ($newsSources as $newsSource)
<option value="{{$newsSource['id']}} : {{$newsSource['name'] }}">{{$newsSource['name']}}</option>
#endforeach
</select>
</label>
<object id="spinner" data="spinner.svg" type="image/svg+xml" hidden></object>
</section>
<div id="news">
<p> News Source : {{$sourceName}} </p>
<section class="news">
#foreach($news as $selectedNews)
<article>
<img src="{{$selectedNews['urlToImage']}}" alt=""/>
<div class="text">
<h1>{{$selectedNews['title']}}</h1>
<p style="font-size: 14px">{{$selectedNews['description']}} <a href="{{$selectedNews['url']}}"
target="_blank">
<small>read more...</small>
</a></p>
<div style="padding-top: 5px;font-size: 12px">
Author: {{$selectedNews['author'] ? : "Unknown" }}</div>
#if($selectedNews['publishedAt'] !== null)
<div style="padding-top: 5px;">Date
Published: {{ Carbon\Carbon::parse($selectedNews['publishedAt'])->format('l jS \\of F Y ') }}</div>
#else
<div style="padding-top: 5px;">Date Published: Unknown</div>
#endif
</div>
</article>
#endforeach
</section>
</div>
</div>
</body>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Scripts -->
<script src="{{ asset('js/site.js') }}"></script>
</html>
apicontroller.php supposed to grab from this to get the news api
<?php
namespace App\Http\Controllers;
use App\Models\Api;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class ApiController extends Controller
{
/**
* #param Request $request
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function displayNews(Request $request)
{
$response = $this->determineMethodHandler($request);
$apiModel = new Api();
$response['news'] = $apiModel->fetchNewsFromSource($response['sourceId']);
$response['newsSources'] = $this->fetchAllNewsSources();
return view('dashboard', $response);
}
/**
* #param $request
* #return mixed
*/
protected function determineMethodHandler($request)
{
if ($request->isMethod('get')) {
$response['sourceName'] = config('app.default_news_source');
$response['sourceId'] = config('app.default_news_source_id');
} else {
$request->validate([
'source' => 'required|string',
]);
$split_input = explode(':', $request->source);
$response['sourceId'] = trim($split_input[0]);
$response['sourceName'] = trim($split_input[1]);
}
return $response;
}
/**
* #return mixed
*/
public function fetchAllNewsSources()
{
$response = Cache::remember('allNewsSources', 22 * 60, function () {
$api = new Api;
return $api->getAllSources();
});
return $response;
}
}

You should pass an array with variables to views
view('dashboard', ["sourceId" => 1, /* and so on */]);
I can't understand what are you doing there.

Related

PHP/Laravel search query controller

I am trying to build a search query to use the user's search input (gene name) and return the gene location and symbol from a JSON file I loaded in.
My Site Controller for the JSON input:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SiteController extends Controller
{
public function index()
{
$results = file_get_contents("http://ftp.ebi.ac.uk/pub/databases/genenames/hgnc/json/locus_groups/protein-coding_gene.json");
$data = json_decode($results, true);
dd($data);
}
}
My Search Controller for the search function:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function search(Request $request){
// Get the search value from the request
$search = $request->input('search');
// Search in the name column from the data table
$data = data::query()
->where('name', 'LIKE', "%{$search}%")
->get();
// Return the search view with the results compacted
return view('search', compact('data'));
}
}
My routes:
<?php
use Illuminate\Support\Facades\Route;
//use App\Http\Controllers\Controller;
use App\Http\Controllers\SiteController;
Route::get('/data', [SiteController::class, 'index']);
Route::get('search', [SearchController::class, 'search']);
Route::get('/', function () {
return view('welcome');
});
And my welcomeblade:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Geisinger</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/1866062af8.js" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="{{ asset('/styles.css') }}" >
</head>
<body>
<img src="{{ asset('/Geisinger_logo.jpg') }}" alt="Geisinger Logo">
<h1> Geisinger Gene Search </h1>
<div class="container my-8 py-5 px-5 mx-5">
<!-- Search input -->
<form action="{{ route('search') }}" method="GET">>
<input type="search" class="form-control" placeholder="Search Gene Name" name="search">
<button type="submit">Search</button>
</form>
<div class="d-grid gap-2 col-6 mx-auto">
<button class="btn btn-outline-dark" type="button">Search <i class="fa-solid fa-magnifying-glass"></i></button>
</div>
<br>
<br>
<h2>Results <i class="fa-solid fa-square-poll-horizontal"></i></h2>
<!-- List items -->
<?php
#if($data->isNotEmpty())
#foreach ($data as $data)
<ul class="list-group mt-3">
<li class="list-group-item">{{ $data->name }}<</li>
<li class="list-group-item">{{ $data->location }}</li>
<li class="list-group-item">{{ $data->symbol }}</li>
</ul>
#endforeach
#else
<div>
<h2>No Gene found</h2>
</div>
#endif
?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
I keep getting "route 'search' not defined" and "syntax error unexpected token "if"". Thank you for your help!
You can only access the route() method on named routes. In your web.php file, you must give your search route the name search before you can access it via route('search')
In you web.php change:
Route::get('search', [SearchController::class, 'search']);
to this:
Route::get('search', [SearchController::class, 'search'])->name('search');
Please visit the docs to learn more.

ngrok returns 419 in laravel 6 with disable CSRF Token

I am using ngrok and laravel 6 to be able to do a project with Transbank, everything is fine at the time of making the POST request, my code
Web Routes
Route::get('/', function () {
return view('webpayplus/welcomeWebPay');
});
Route::post('/started', 'WebPayPlussController#initPayWeb')->name('start');
Route::post('/confirm_pay', 'WebPayPlussController#confirmPay')->name('front');
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Transbank\Webpay\WebpayPlus;
use Transbank\Webpay\WebpayPlus\Transaction;
class WebPayPlussController extends Controller
{
public function __construct(){
WebpayPlus::configureForIntegration('597055555532', '579B532A7440BB0C9079DED94D31EA1615BACEB56610332264630D42D0A36B1C');
}
public function initPayWeb(Request $request){
$buy_order ='abc456';
$session_id='4784568';
$amount=10000;
$response = (new Transaction)->create(
$buy_order,
$session_id,
$amount,
Route('front'));
$url =$response->getUrl().'?token_ws='.$response->getToken();
return redirect()->away($url);
}
public function confirmPay(Request $request){
$confirm= (new Transaction)->commit($request->get('token_ws'));
if($confirmacion->isApproved()){
return 'is Approved';
}else{
return 'is not Approved';
}
}
}
view blade php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transbank</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card mb-4">
<div class="card-body">
<h5 class="card-title" >Web Pay Plus</h5>
<p class="card-text"> Pagos con WebPayPlus</p>
<form method="POST" action="{{route('start')}}" >
#csrf
<input type="submit" class="btn btn-sm btn-primary" value="Enviar">
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
What I do is start the php artisan server --host = my-ip-address --port = 8000 then i run for ngrok ngrok http my-ip-address: 8000 getting the url from ngrok, but when starting the "started" route directs Transbank, the problem is when returning the URL to the "confirm_pay" route it shows a 419 error, the page expired.
I have tried disabling CSRF checking in VerifyCsrfToken as follows
class VerifyCsrfToken
{
use InteractsWithTime;
protected $except = [
'confirm_pay/confirmPay',
'started/initPayWeb'
];
}
but i keep getting this problem
Just add the code below in app/providers/AppServiceProvider.php
public function boot()
{
if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
\URL::forceScheme('https');
}
}

Unable to send HTML email in Laravel 5.8

I am having a difficult time sending HTML email through my Laravel application. I have tried to return the view and it returns well but when I send the email to an actual email, it arrives as a plain text email without all the HTML parsing.
My View layout for the email is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap"
rel="stylesheet">
<!-- Bootstrap CSS File -->
<link href="{{ url('design-assets/lib/bootstrap/css/bootstrap.min.css')}}"
rel="stylesheet">
<!-- Main Stylesheet File -->
<link href="{{ url('design-assets/css/style.css" rel="stylesheet')}}">
<link href="{{ url('design-assets/css/prof-custom.css')}}"
rel="stylesheet">
#yield('styles')
</head>
<body id="body">
#yield('content')
<!-- JavaScript Libraries -->
<script src="{{ url('design-assets/lib/jquery/jquery.min.js')}}"></script>
<script src="{{ url('design-assets/lib/jquery/jquery-migrate.min.js')}}">
</script>
<script src="{{ url('design-assets/lib/bootstrap/js/bootstrap.bundle.min.js') }}/"></script>
<!-- Contact Form JavaScript File -->
<!-- Template Main Javascript File -->
<script src="{{ url('design-assets/js/main.js') }}"></script>
#yield('scripts')
</body>
The actual email view is as follows:
#extends('layouts.mail')
#section('content')
<div class="card montserrat-font">
<div class="card-header">
<div class="card-title">Contact Message from the Website</div>
</div>
<div class="card-body">
<div class="card-text">
Dear Sir,<br /><br />
We have a contact from our events website with the following details<br/><br />
</div>
<div class="table-responsive">
<table class="table table-striped">
<tr>
<th>Name of Sender:</th><td>{{$mail_info['name']}}</td>
</tr>
<tr>
<th>Email of Sender:</th><td>{{$mail_info['email']}}</td>
</tr>
<tr>
<th>Phone number of Sender:</th><td>{{$mail_info['phone']}}</td>
</tr>
<tr>
<th>Subject of Message:</th><td>{{$mail_info['subject']}}</td>
</tr>
{{-- <tr>
<th>Message:</th><td>{{$mail_info['message']}}</td>
</tr> --}}
</table>
</div>
<div class="card-title">Message body</div>
<div class="card-text">
{!! $mail_info['message'] !!}
</div>
</div>
</div>
#endsection
The problem is that when I check the format returned from the email view by returning the view as follows:
return new \App\Mail\ContactMail(['email' => 'testemail#gmail.com', 'name' => 'Testing Name','phone'=>'08033776502', 'subject' => 'Just a test', 'message' => "This is a message returned from testing the view email template"]);
I get a view that represents exactly what I want but when I send the email, it arrives as a plain text email
This is how I call the view through mailable class
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class ContactMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $mail_info;
public function __construct($mail_info_array)
{
$this->mail_info = $mail_info_array;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
// return $this->view('view.name');
return $this->view('mails.web-contact', ['mail_info'=>$this->mail_info]);
}
}
and then through the controller as follows:
public function post_contact(Request $request)
{
try
{
$data = $request->all();
$this->validate_recaptcher($data['g-recaptcha-response']);
$this->validator($request->all())->validate();
\Mail::to('uchendukwe#yahoo.com')->send(new \App\Mail\ContactMail(['email' => $request->email, 'name' => $request->name,'phone'=>$request->phone, 'subject' => $request->subject, 'message' => $request->message]));
return redirect()->route('ContactForm')->with('msg',"<div class='alert alert-success'><span class='fa fa-check'></span> Message successfully sent. I will get back to you soon if necessary</div>");
// return new \App\Mail\ContactMail(['email' => $request->email, 'name'=> $request->name,'phone'=>$request->phone, 'subject' => $request->subject, 'message' => $request->message]);
}
catch(Exception $e)
{
return back()->withInputs()->with('msg',"<div class='alert alert-danger'><span class='fa fa-warning'></span> ".$e->getMessage()."</div>");
}
}
I am using smtp email driver and every other thing is working as expected.
I will appreciate any guide to resolve this
Thank you
Add your styles inline in the head portion of your email layout. Mail clients tend to ignore externally referenced css. Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
...
<style type="text/css">
your custom styles here
</style>
...
</head>
</html>
You can accomplish this using Markdown.
Customizing The CSS
After exporting the components, the resources/views/vendor/mail/html/themes directory will contain a default.css file. You may customize the CSS in this file and your styles will automatically be in-lined within the HTML representations of your Markdown mail messages.

Laravel yield and extends not working

This is master.blade.php placed in views folder
<html ng-app="planner">
<head>
<title>MeetUp Planner</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/master.css" type="text/css">
</head>
<body ng-controller="MainController">
<div class="container" ng-controller="MainController">
<div class="row row-centered planner-block">
<div class="col-md-12">
<div class="col-md-5 col-centered col-min form-area">
<div class="row row-centered">
#yield('signup')
</div>
</div>
</div>
</div>
</div>
<script src="js/master.js"></script>
</body>
</html>
This is forms/signup.blade.php place in views folder
#extends('master')
#section('signup')
<div class="col-md-11 col-centered form-area-inner">
<span class="form-text">Sign Up</span>
<hr class="seperator"/>
</div>
#stop
This is routes file
<?php
Route::get('/', function () {
return view('master');
});
The yield 'signup' is not wokring, the divs and text are not being show in the master file. What could be the problem?
Directory Structure
resources:
---views->errors
---views->forms->signup.blade.php
---views->vendor
---views->master.blade.php
Using laravel 5.2
That's not how it works. master view will be extended when you'll use forms.signup view:
Route::get('/', function () {
return view('forms.signup');
});
If you want to include some view into master view, you should use #include() clause.
your route file will be
<?php
Route::get('/', function () {
return view('forms.signup');
});
?>
change the location of master.blade.php
move it to ---resources/views/layouts/master.blade.php
in your master.blade.php file change this line
#yield('signup') to #yield('content')
reference link : link

Passing variable to view by with not working in laravel 5.1

I want to pass my variable to view by with
this is my controller for example :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Prices ;
class PricesController extends Controller
{
function getIndex()
{
$prices = Prices::orderBy( 'id' , 'desc' )-> paginate(2) ;
return view('home')->nest('content' , 'price', compact('prices') ) ->with( [ 'title' => 'prices page' , 'message' => 'my message text ' ]) ;
}
}
and this is my master.blade.php :
<!doctype html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> {{ $title }}</title>
<link rel="stylesheet" href="{{ url() }}/css/bootstrap.css">
<link rel="stylesheet" href="{{ url() }}/css/style.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
#yield("main")
</div><!-- container -->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="{{ url() }}/js/bootstrap.min.js"></script>
<script src="{{ url() }}/js/dropdown.js"></script>
<script src="{{ url() }}/js/collapse.js"></script>
<script src="{{ url() }}/js/transition.js"></script>
<script src="{{ url() }}/js/tab.js"></script>
</body>
</html>
and this is home.blade.php :
#extends('master')
#section('main')
#include('top_menu')
<div class="row">
<section class="col-sm-12 col-md-12 content">
<div class="row">
<section class="col-md-12">
<div class="in">
{!! $content !!}
</div>
</section>
</div>
</section>
</div>
#stop
and this is my price.blade.php :
#if( empty($prices) )
<div class="alert alert-warning">
No result
</div>
#else
#if( ! isset( $message) )
No message
#else
{{ $message }}
#endif
<table class="table table-striped">
<tr>
<th>name</th>
<th>yeat</th>
<th>qnty </th>
</tr>
#foreach( $prices as $price )
<tr>
<td> {{$price->product}} </td>
<td> {{$price->yaer}} </td>
<td> {{$price->quantity}} </td>
</tr>
#endforeach
</table>
<center> {!! $prices->render() !!} </center>
#endif
in Output title in <title> {{ $title }}</title> in master.balde.php
is passed good and it will show : prices page in page title , But in this part in price.blade.php :
#if( ! isset( $message) )
No message
#else
{{ $message }}
#endif
the output is :
No maessage
I can access to $message and $title in home.blade.php , But no in price.blade.php
how can I fix it ?
You have an error in a word - maessage, maybe you sending message, but trying to use maessage. Please check it.
Update:
Your code now looks fine. However, look at #if (empty($prices)) part. If (empty($prices) returns true, your code with $message part will never be executed. Probably that's why you don't see my message text.
Update 2:
return view('home')
->nest('content', 'price', array(
'prices' => $prices,
'title' => 'prices page',
'message' => 'my message text'
))
->with([ 'title' => 'prices page', 'message' => 'my message text']);

Categories