Laravel and unique slugs - php

I'm trying to generate an get unique slugs, just like MyBB does, but it doens't work well...
I'm using the plugin https://github.com/cviebrock/eloquent-sluggable/tree/2.x for Laravel 4.2.
So I got this:
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
class ForumController extends \BaseController implements SluggableInterface {
use SluggableTrait;
protected $sluggable = [
'build_from' => 'title',
'save_to' => 'slug',
];
And in that Class, I don't know how I need to generate the slug,
it needs to be generated in this function:
public function PostTopic($cid)
{
//Get all the data and store it inside Store Variable
$data = Input::all();
// Make's messages of faults
$messages = array(
'title.required' => 'U moet een titel opgeven!',
'titel.unique' => 'De opgegeven titel bestaat al, gebruik een andere.',
'message.required' => 'u moet een bericht opgeven!',
'spamprt' => 'honeypot', //spam protection
'time' => 'required|honeytime:60'
);
$rules = array(
'title' => 'required',
'message' => 'required'
);
$validator = Validator::make($data, $rules, $messages);
//process the storage
if ($validator->fails())
{
return Redirect::back()->with('errors', $validator->errors())->withInput();
}else{
//store
$thread = new Thread;
$thread->cid = $cid;
$thread->title = Input::get('title');
$thread->message = Input::get('message');
$thread->prefix = 0;
$thread->uid = Auth::id();
$thread->username = Auth::user()->username;
$thread->date_posted = Carbon\Carbon::now();
$thread->save();
Session::put('_token', sha1(microtime()));
//redirect
return Redirect::back()->with('message', 'Uw bericht is succesvol geplaatst!');
}
}
But how? And how do I need to get the slugs to display them in an URL or so?

Related

How to pass arguments to seeder from controller method in Laravel?

I'd like to create a dynamic model.
In fact, I have this seeder :
class TestSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('tests')->insert([
'name_test' => $name_test
]);
}
}
And I need to send arguments from my controller :
public function addTest(Request $request)
{
$request->validate([
'name_test' => 'required|max:255'
], [
'name_test.required' => 'Es necesario rellenar el campo de nombre',
'name_test.max' => 'El nombre del test debe ser máxim de 255 catacteres',
]);
$input = $request->all();
//$test = Test::create($input);
return back()->with('success', 'El test se ha creado correctamente.');
}
However, I have no idea how I can do it.
Any ideas ?
You can just call the TestSeeder class directly:
$test = new TestSeeder;
$test->run($request->name_test);
public function run($name_test)
{
DB::table('tests')->insert([
'name_test' => $name_test
]);
}
However, the seeder classes in Laravel are meant for initial data set up, when running tests or when you want to regularly refresh the database in your local environment, for example. You're better off to just run the insert right in the controller - nothing wrong with that when you're testing!
in controller:
$data = new \Database\Seeders\DomainDemoDataSeeder();
$data->run($request->domain_id, $request->id);
in seeder:
public function run($domainId, $userId) {
$uiPages = [
[
'name' => 'header',
],
[
'name' => 'footer'
],
[
'name' => 'home',
],
[
'name' => 'about',
]
];
foreach ($uiPages as $uiPage) {
UiPages::create([
'name' => $uiPage['name'],
'user_id' => $userId,
'domain_id' => $domainId
]);
}
}

Remove imgur from uploading images

A few months ago a friend of mine added in my cms created in laravel the upload of images via imgur, only that I would like to remove it, on the cms however the images are saved (locally) I would like to remove the upload on imgur and I would like to stay the images locally
public function imageProfile(Request $request)
{
$user = Auth::user();
$rules = array(
'profile-image' => 'required|image|mimes:jpeg,png,jpg,gif|max:8192|dimensions:min_width=160,min_height=160',
);
$customMessages = [
'profile-image.required' => 'E\' richiesta una immagine per cambiare immagine di profilo.',
'profile-image.image' => 'Devi inserire un immagine valida.',
'profile-image.mimes' => 'L\'immagine inserita non ha un formato adatto.',
'profile-image.dimensions' => 'L\'immagine deve essere minimo 160x160.',
];
$validator = Validator::make(Input::all(), $rules, $customMessages);
if ($validator->fails()) {
return response()->json(['success' => false, 'error' => $this->validationErrorsToString($validator->errors())]);
}
if ($request->hasFile('profile-image')) {
$number = mt_rand(1,1000000);
$image = $request->file('profile-image');
$name = $user->username.'-'.Carbon::now()->toDateString().'-'.$number.'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/profile');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$image = Imgur::setHeaders([
'headers' => [
'authorization' => 'Client-ID MY CLIENT ID',
'content-type' => 'application/x-www-form-urlencoded',
]
])->setFormParams([
'form_params' => [
'image' => URL::to("/").'/uploads/profile/'. $name,
]
])->upload(URL::to("/").'/uploads/profile/'. $name);
\File::delete('uploads/profile/' .$name);
$user->image_profile = $image->link();
$user->save();
$html = $image->link();
return response()->json(['success' => true, 'html' => $html, 'image' => $image->link()]);
}
}
My server is running Ubuntu 16.04 + Laravel 5.5
Best Regards
This code will only upload photo to your local directory.
public function imageProfile(Request $request)
{
$user = Auth::user();
$rules = array(
'profile-image' => 'required|image|mimes:jpeg,png,jpg,gif|max:8192|dimensions:min_width=160,min_height=160',
);
$customMessages = [
'profile-image.required' => 'E\' richiesta una immagine per cambiare immagine di profilo.',
'profile-image.image' => 'Devi inserire un immagine valida.',
'profile-image.mimes' => 'L\'immagine inserita non ha un formato adatto.',
'profile-image.dimensions' => 'L\'immagine deve essere minimo 160x160.',
];
$validator = Validator::make(Input::all(), $rules, $customMessages);
if ($validator->fails()) {
return response()->json(['success' => false, 'error' => $this->validationErrorsToString($validator->errors())]);
}
if ($request->hasFile('profile-image')) {
$number = mt_rand(1,1000000);
$image = $request->file('profile-image');
$name = $user->username.'-'.Carbon::now()->toDateString().'-'.$number.'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/profile');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
// remove this commented portion
// $image = Imgur::setHeaders([
// 'headers' => [
// 'authorization' => 'Client-ID MY CLIENT ID',
// 'content-type' => 'application/x-www-form-urlencoded',
// ]
// ])->setFormParams([
// 'form_params' => [
// 'image' => URL::to("/").'/uploads/profile/'. $name,
// ]
// ])->upload(URL::to("/").'/uploads/profile/'. $name);
// \File::delete('uploads/profile/' .$name);
// $user->image_profile = $image->link();
// $user->save();
// $html = $image->link();
// update this portion to
$user->image_profile = $imagePath;
$user->save();
$html = $imagePath;
// return response()->json(['success' => true, 'html' => $html, 'image' => $image->link()]);
// also update this portion to
return response()->json(['success' => true, 'html' => $html, 'image' => $imagePath]);
}
}

CodeIgniter 404 Page Not Found with another controller

First of all I want to apologize for my English, =). I am making a web application but when redirecting program flow to another controllador I get this error: "404 Page Not Found". The classes and files are capitalized as I have read in other posts and that might not be. Thanks in advance.
This is the main controller (Auth Controller) that calls to "Activity" with "redirect":
class Auth extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
redirect('auth/login');
}
public function login() {
if (!$this->input->post())
{
$this->load->view('templates/main_template', array(
'title' => 'Login',
'header' => $this->load->view('templates/header', null, TRUE),
'content' => $this->load->view('pages/login', null, TRUE),
'footer' => $this->load->view('templates/footer', null, TRUE)
));
return;
}
$this->form_validation->set_rules('useremail', 'Useremail', 'trim|required|xss_clean'); // trim: quita espacios; required: campo requerido; xss_clean: elimina posibles inyecciones sql; callback_user_auth: otras funciones y llamadas, en este caso llamada a funciónq que autentifica al usuario
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_user_auth'); // |callback_user_auth
if ($this->form_validation->run() == FALSE)
{
// LOGIN VIEW (home)
$this->load->view('templates/main_template', array(
'title' => 'Login',
'header' => $this->load->view('templates/header', null, TRUE),
'content' => $this->load->view('pages/login', null, TRUE),
'footer' => $this->load->view('templates/footer', null, TRUE)
));;
} else {
redirect('activity/list_actividades');
}
}
public function user_auth($password) {
$useremail = $this->input->post('useremail');
$user = $this->User_model->authenticate($useremail, $password);
if ($user)
{
// valid user, set session data
$this->session->logged_in = array(
'useremail' => $user->email,
'username' => $user->name,
'group' => $user->group // CAMBIO EN LA BASE DE DATOS
); // GROUP POR ADMIN. DEPENDIENDO DEL GRUPO SE TIENEN UNOS PERMISOS U OTROS
return TRUE;
}
$this->form_validation->set_message('user_auth', 'Invalid username or password');
return FALSE;
}
public function logout() {
unset($_SESSION['logged_in']);
redirect('auth/login');
}
Activity Controller:
class Activity extends CI_Controller {
public function __construct() {
parent::__construct();
// check for the session here... in theory
}
public function index() {
redirect('auth/login');
}
public function list_actividades () {
$this->load->model('Activity_model');
$data['actividades'] = $this->Activity_model->getAll();
$data['grupo_usuario'] = $this->session->logged_in['group'];
$this->load->view('templates/main_template', array(
'title' => 'Lista de Actividades',
'header' => $this->load->view('templates/header', null, TRUE),
'content' => $this->load->view('templates/lista_actividades', $data, TRUE),
'footer' => $this->load->view('templates/footer', null, TRUE)
));
}
There is a */ in your function list_actividades
it might be possible that CodeIgniter ignores the error, but couldn't read the class because of it, resulting in a 404
OK, it finally was that when you are using authorization hook you have to register the authorized addresses in the acl.php file.

zend 2 - custom field name in validation message

I would like to customize input name to show in my view when happen an error in validation of the form
$this->add(array(
'name' => 'generica_descricao', // I WOULD LIKE TO CALL HIM DESCRIÇÃO
//'custom_name' => 'Descrição',
'required' => true,
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'messages' => array(
'isEmpty' => 'O campo não pode ser vazio'
),
),
),
));
and when i call getMessage() as the code above
if (!$form->isValid()) {
$resultado = new Resultado(Resultado::FLAG_WARNING, $form->getMessages());
$resultado->setaRetornoLayoutErro($this->getServiceLocator());
return $resultado->getJson();
}
they will return
array('Descrição' => 'O campo não pode ser vazio');
then i will can give this array to my view and show dialog with the correctly messages, can anybody help how do that in zend?
I found a best way, create a new method that extends the default form getting the name from the label in the form.
abstract class GenericForm extends Form {
public function getMessagesTranslated($elementName = null) {
$mensagensOriginais = $this->getMessages($elementName);
foreach ($mensagensOriginais as $chave => $mensagens) {
$label = TranslateUtil::translate($this->get($chave)->getLabel());
$mensagensOriginais[$label] = $mensagensOriginais[$chave];
unset($mensagensOriginais[$chave]);
}
return mensagensOriginais;
}
I customize my filter with a method that translates the field name, is not what i want but it works for now:
generic filter
abstract function convertErrorsArrayKeyToFriendlyNames($erros);
specific filter:
public function convertErrorsArrayKeyToFriendlyNames($erros) {
foreach ($erros as $chave => $valor) {
if ($chave == 'generica_descricao') {
$erros['Descrição'] = $erros[$chave];
unset($erros[$chave]);
} else if ($chave == 'generica_ordem') {
$erros['Ordem'] = $erros[$chave];
unset($erros[$chave]);
} else if ($chave == 'generica_ativo') {
$erros['Ativo'] = $erros[$chave];
unset($erros[$chave]);
}
}
return $erros;
}
and in the controller
if (!$form->isValid()) {
$erros = $filtro->convertErrorsArrayKeyToFriendlyNames($form->getMessages());
$resultado = new Resultado(Resultado::FLAG_WARNING, $erros);
$resultado->setaRetornoLayoutErro($this->getServiceLocator());
return $resultado->getJson();
}

How I can make authentication using my own class in laravel?

I'm trying to do a basic authentication which considers email and password. My problem comes when I call the method Auth :: attempt I get the following error.
Model
class Usuario extends Eloquent{
protected $table = 'Usuario';
protected $primaryKey = 'idUsuario';
protected $fillable = array('Nombre',
'Apellido',
'TipoUsuario',
'Contrasena',
'Correo',
'Telefono');
}
Controller
class UsuarioController extends BaseController{
public function doLogin(){
$rules = array('correo' => 'required|email',
'contrasena' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::to('usuario')
->withErrors($validator)// manda los errores al login
->withInput(Input::except('contrasena')); //
}else{
$userData = array(
'Correo' => Input::get('correo'),
'Contrasena' => Input::get('contrasena')
);
if(Auth::attempt($userData)){
echo 'bien';
}else{
return Redirect::to('login');
}
}
}
public function showLogin(){
return View::make('login');
}
}
Routte
Route::get('usuario', array('uses' => 'UsuarioController#showLogin'));
Route::post('usuario', array('uses' => 'UsuarioController#doLogin'));
Auth.php
return array(
'driver' => 'database',
'model' => 'User',
'table' => 'Usuario',
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
In the process of checking user credentials Laravel calls validateCredentials method when Auth::attempt gets called and in this function (given below) Laravel checks for the password key in the passed array and in your case you are not passing a password key so the error happens.
public function validateCredentials(UserInterface $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
Change the key in the $userData array:
$userData = array(
'email' => Input::get('correo'), // If correo means email
'password' => Input::get('contrasena') // If contrasena means password
);
Also make changes in your database table's field names which represents users table, I think it's your Usuario table.
I'd check to make sure you're passing the correct info to Auth::attempt() in your controller. I use something more like:
$userData = array('email' => Input::get('email'), 'password' => Input::get('password'));

Categories