Twitter API app, does not showing pictures or videos - laravel

I created Twitter API app in Laravel. The application provide very weird layout. I cannot set up profile picture, or picture for tweet. I am getting only text pretty much.
I spent whole day to figure out, why my APP does not have picture, url or videos.
I appreciate any suggestions what might be wrong
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="sha384-
UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/"
crossorigin="anonymous">
<link rel="stylesheet" href="{{asset('/css/app.css')}}">
<title>Nancy's Twitter API App</title>
</head>
<body>
<h1 class="text-info text-center mt-5">Nancy's Tweets Api</h1>
<div class="container">
<div class="col align-self-center mb-5">
<form class="well" action="{{route('post.tweet')}}"
method="POST" enctype="multipart/form-data">
#csrf
#if(count($errors) > 0)
#foreach ($errors->all() as $error)
<div class="alert alert-danger"> {{$error}}</div>
#endforeach
#endif
<div class="form-group">
<label>Your Tweet</label>
<textarea class="form-control" name="tweet"
rows="3"></textarea>
</div>
<div class="form-group">
<label>Upload Filet</label>
<input type="file" class="form-control-file"
name="images[]" multiple>
</div>
<div class="from-group">
<button class="btn btn-success">Create
Tweet</button>
</div>
</form>
</div>
</div>
<div class="container">
<h3>Tweets:</h3>
#if(!empty($data))
#foreach ($data as $key => $tweet )
<div class="card text-primary bg-white mb-3" style="max-width:
150rem;">
<div class="card-body">
<p class="card-text"><h3>{{$tweet->text}}</h3></p>
#if(!empty($tweet->extented_entities->media)){
#foreach ($tweet->extented_entities->media as $i)
<img src="{{$i->media_url_https}}"
style="width:100px;">
#endforeach}
#endif
<div class="card-header">
<i class="fas fa-heart">{{$tweet-
>favorite_count}}</i>
<i class="fas fa-redo"> {{$tweet-
>retweet_count}}</i>
</div>
</div>
</div>
#endforeach
#else
<p>No Tweets Found</p>
#endif
</div>
</body>
</html>
class TwitterController extends Controller
{
//
public function twitterUserTimeline(){
$count = 10;
$format = 'array';
$data = Twitter::getUserTimeline([$count, $format]);
return view('twitter', compact('data'));
}
public function tweet(Request $request){
$this->validate($request, [
'tweet' => 'required'
]);
$newTweet = ['status' => $request->tweet];
if(!empty($request->images)){
foreach($request->images as $key => $value){
$uploadMedia = Twitter::uploadMedia(['media' => File::get($value-
>getRealPath())]);
if(!empty($uploadMedia)){
$newTweet['media_ids'][$uploadMedia->media_id_string] =
$uploadMedia->media_id_string;
}
}
}
$twitter = Twitter::postTweet($newTweet);
return back();
}
}

Related

ajax laravel not inserting or code not working

i want to insert to the database by ajax crud i am inserting but the code dosn't work iam using jquery javascript framework
i want to insert to the database by ajax crud i am inserting but the code dosn't work iam using jquery javascript framework
i dont' know why although i am writing correctly
please help
here is my code
my blade file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="{{asset('css/app.css')}}">
</head>
<body>
<div class="container">
<div class="row" style="matgin-top:50px;">
<div class="col-md-6">
<div class="card">
<div class="card-hehader bg-primary text-white">Add new product</div>
<form id="form" action="{{route('products.store')}}" method="post" enctype="multipart/form-data">
#csrf
#method('POST')
<div class="form-group">
<label for="">product name</label>
<input type="text" name="name" class="form-control">
<span class="text-danger error-text product_name_error"></span>
</div>
<div class="form-group">
<label for="">product image</label>
<input type="file" name="image" class="form-control">
<span class="text-danger error-text product_name_error"></span>
</div>
<button type="submit" class="btn btn-info">add</button>
</form>
</div>
</div>
<div class="col-md-6">
<div class="card">
<div class="card-header bg-primary">All Products</div>
<div class="card-body">
</div>
</div>
</div>
</div>
</div>
<script src="{{asset('js/app.js')}}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
e.preventDefault();
var form = this;
$.ajax({
url:$(form).attr('action'),
method:$(form).attr('method'),
data:new FormData(form),
processData:false,
dataType:'json',
contentType:false,
beforeSend:function(){
$(form).find('span.error-text').text('');
},
succes:function(data){
if(data.code == 0){
$.each(data.error, function(prefix,val){
$(form).find('span.'+prefix+'_error').text(val[0]);
});
}
else{
$(form)[0].reset();
alert(data.msg);
// fetchAllProducts();
}
}
})
});
});
</script>
</body>
</html>
and my controller store function
public function store(Request $request)
{
$path = 'files/';
$file = $request->file('product_image');
$file_name = time().'_'.$file->getClientOriginalName();
// $upload = $file->storeAs($path, $file_name);
$upload = $file->storeAs($path, $file_name, 'public');
if($upload){
Product::insert([
'name'=>$request->name,
'image'=>$request->image,
]);
return response()->json(['code'=>1,'msg'=>'New product has been saved successfully']);
}
}
I check out your controller portion and found something messy, would you mind trying with the below code:
if ($request->has('image')) {
$fileName = time() . '_' . $request->image->getClientOriginalExtension();
$request->image->storeAs('Files', $fileName, 'image');
$product = new Product();
$product->name = $request->name;
$product->image = $fileName;
$product->save();
return response()->json(['code'=>1,'msg'=>'New product has been saved
successfully']);
}

ErrorException Array to string conversion

i am facing ErrorException Array to string conversion, I am new in laravel. please help me in detail if you can,please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can
This is my code
<?php
namespace App\Http\Controllers;
use Redirect,Response;
use Illuminate\Http\Request;
use App\Models\Test;
use File;
class JsonController extends Controller
{
public function index()
{
return view('json_form');
}
public function download(Request $request)
{
$data = $request->only('name','email','mobile_number');
$test['token'] = time();
$test['data'] = json_encode($data);
Test::insert($test);
$fileName = $test['token']. '_datafile.json';
File::put(public_path('/upload/json/'.$fileName),$test);
//return download(public_path('/upload/jsonfile/'.$fileName));
$headers = [ 'Content-Type' => 'application/json', ];
return response()->download($test, 'filename.json', $headers);
//return response()->download(public_path('file_path/from_public_dir.pdf'));
}
}
This is my jeson.blade.php
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Store Data To Json Format In Database - Tutsmake.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<style>
.error{ color:red; }
</style>
</head>
<body>
<div class="container">
<h2 style="margin-top: 10px;">Laravel Store Data To Json Format In Database - Tutsmake.com</h2>
<br>
<br>
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<br>
#endif
<form id="laravel_json" method="post" action="json-file-download">
#csrf
<div class="form-group">
<label for="formGroupExampleInput">Name</label>
<input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
</div>
<div class="form-group">
<label for="email">Email Id</label>
<input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
</div>
<div class="form-group">
<label for="mobile_number">Mobile Number</label>
<input type="text" name="mobile_number" class="form-control" id="mobile_number" placeholder="Please enter mobile number">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</body>
</html>

Laravel: Login system problem for learning

I'm trying to make a login for learning, so I followed a video from youtube with the same coding. It should be able to check the format of the inputted data, check whether user already login or not, check whether user accessing the next page wihthout login, but in the end, it will always only showed email and password required errors even if I already inputted the right input. Please help. Here are my codes.
web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/main', 'MainController#index');
Route::post('/main/checklogin', 'MainController#checklogin');
Route::get('main/successlogin', 'MainController#successlogin');
Route::get('main/logout', 'MainController#logout');
login.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Login</title>
<!--CSS-->
<link rel="stylesheet" href="{{ asset('css/styles.css') }}" type="text/css">
<link rel="stylesheet" href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' />
<script type="text/javascript" src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
</head>
<body>
<div class="login-page-frame">
<div class="header-login-page-frame">
<h3>Login</h3>
</div>
<div class="inner-login-form-frame">
#if(isset(Auth::user()->email))
<script>window.location="/main/successlogin";</script>
#endif
#if($message = Session::get('error'))
<div class="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert"></button>
<strong>{{$message}}</strong>
</div>
#endif
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ url('/main/checklogin') }}" class="login-form">
{{ csrf_field() }}
<input type="email" placeholder="email" name="login-email" class="form-control">
<br>
<input type="password" placeholder="pass" name="login-password" class="form-control">
<br>
<input type="submit" name="login" class="btn-login" value="login">
</form>
</div>
</div>
</body>
</html>
halamanUtama.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Halaman Utama</title>
</head>
<body>
<div class="container box">
<h3 align="center">Selamat Datang</h3>
<br />
#if(isset(Auth::user()->email))
<div class="alert alert-danger success-block">
<strong>Welcome {{ Auth::user()->email }}</strong>
<br />
Logout
</div>
else
<script>window.location="/main";</script>
#endif
</div>
</body>
</html>
MainController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
use Input;
class MainController extends Controller
{
//
function index(){
return view('login');
}
function checklogin(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
]);
$user_data=array(
'email' => $request->get('login-email'),
'password' => $request->get('login-password')
);
if(Auth::attempt($user_data)){
return redirect('main/successlogin');
}else{
return back()->with('error', 'Wrong Login Details');
}
}
function successlogin(){
return view('halamanUtama');
}
function logout(){
Auth::logout();
return redirect('main');
}
}
I won't comment on whether any of your other code works, but the cause of your validation errors is that the name of your form inputs does not match the name of the fields you are trying to validate.
In your form, your inputs are called login-email and login-password. However, in your controller, you are validating that a field called email and a field called password are provided (because they are required).
So either change your form names to email and password or change your validation fields to login-email and login-password.

The email field is required but no input email in view Laravel

I keep getting this error message:
The email field is required.
But I don't have any input type with a name of email in my view:
Login
<link rel="shortcut icon" href="{{ asset('img/logo.png') }}" type="image/x-icon">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,800" rel="stylesheet">
<link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}">
<link rel="stylesheet" href="{{ asset('css/feather.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
<link rel="stylesheet" href="{{ asset('css/jquery.mCustomScrollbar.css') }}">
</head>
<body>
<section class="login-block">
<div class="container">
<div class="row">
<div class="col-md-12">
<form action="/login" method="post" class="md-float-material form-material">
#csrf
<div class="auth-box card">
<div class="card-block">
<div class="row m-b-20">
<div class="col-md-12">
<h3 class="text-center">Members Management System</h3>
</div>
</div>
#if ($errors)
<div class="alert alert-danger background-danger">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<i class="icofont icofont-close-line-circled text-white"></i>
</button>
#foreach ($errors->all() as $error)
- {{ $error }}
<br>
#endforeach
</div>
#endif
<div class="form-group form-primary">
<input type="text" name="employee_id" class="form-control" required=""
placeholder="Employee ID">
<span class="form-bar"></span>
</div>
<div class="form-group form-primary">
<input type="password" name="password" class="form-control" required=""
placeholder="Password">
<span class="form-bar"></span>
</div>
<div class="row m-t-30">
<div class="col-md-12">
<button type="submit"
class="btn btn-primary btn-md btn-block waves-effect waves-light text-center m-b-20">
SIGN IN
</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
<script src="{{ asset('js/jquery.min.js') }}"></script>
<script src="{{ asset('js/jquery-ui.min.js') }}"></script>
<script src="{{ asset('js/script.js') }}"></script>
</body>
</html>
I don't understand why the $errors is notifying me of error regarding email. Any suggestions? I didn't modify any default AUTH settings from Laravel. It may seem that the error is coming from other source?
EDIT:
Thanks for suggesting to override the username() in my LoginController by:
public function username()
{
return 'employee_id';
}
Is this the most conventional and preferred way to do this? Thank you for the assist.
AuthenticatesUsers is responsible for validating the data after the user submitted the form. If you take a look at this file, you will see this method:
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
More specifically, as you can see, this method is in charge for calling the validator on the fields name "password" and by the method username(). If you only wanted to custom the username field, you could overwrite the username() method in LoginController class:
public function username()
{
return 'employee_id';
}
But since you want to custom both the username field name and the password field name, I suggest that you overwrite the validateLogin() method in the LoginController class:
protected function validateLogin(Request $request)
{
$this->validate($request, [
'employee_id' => 'required|string',
'user_password' => 'required|string',
]);
}
Hope that helps.
You can refer employee_id, as username, on login.
Now, open LoginController, and add the username() method.
public function username() {
return "username";
}
Now, you can login without e-mail address.

laravel using withErrors in a try catch

So i'm making this website where you can buy game consoles, so I made a crud, but I wanted that it was impossible to insert duplicates in the database, but when I create a dupicate you get a laravel error and that is not user friendly. So I wanted to show a normal message saying that you made a duplicate. so I made this.
public function store(Request $request)
{
try
{
$consoles = new consoles();
$consoles->naam = input::get('naam');
$consoles->releasedate = input::get('releasedate');
$consoles->company = input::get('company');
$consoles->price = input::get('price');
$consoles->created_at = null;
$consoles->updated_at = null;
$consoles->save();
}catch (\Exception $e)
{
return Redirect::to('console/create')
->withInput()
->withErrors(array('message' => 'duplicate'));
}
return redirect('consoles');
}
the problem is that ->withErrors(array('message' => 'duplicate')) doesn't show anything. what am I doing wrong.
EDIT
create.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker({ dateFormat: 'yy-mm-dd' }).val();
} );
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading"> creating data</div>
<form method="POST" action="{{url('games/store/')}}">
naam: <br>
<input type="text" name="naam" required>*required<br>
releasedate: <br>
<input type="text" name="releasedate" id="datepicker" required>*required<br>
company: <br>
<input type="text" name="company" required>*required<br>
price: <br>
<input type="number" name="price" min="0" value="0" step=".01" required>*required<br>
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<input type="submit" name="create" value="create">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
When you set withErrors you don't need to pass the array, just write the error message like this ->withErrors('Duplicate');
In the view remember to include a check if there are errors
#if ($errors->count())
<div class="col-md-12">
<div class="alert alert-danger text-center">
#foreach ($errors->all() as $error)
<p>{{$error}}</p>
#endforeach
</div>
</div>
#endif
You can simply use with() to send the message to the view like
return Redirect::to('console/create')
->withInput()
->with('message', 'duplicate');
and access that in view as
#if ($message = Session::get('message'))
{{$message}}
#endif

Resources