<repo_name>crisgonzalez94/laravel-red-social<file_sep>/app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
//Esta la necesitamos para enviar archivos a la vista
use Illuminate\Http\Response;
//Dependencias para la subida de archivos
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

class UserController extends Controller{

    public function __construct(){
        //Midleware de atuenticacion
        $this->middleware('auth');
    }

    public function config(){
        return view('user.config');
    }

    /*=============================================================================*/
    /*Metodo Actualizar usuario*/
    public function update(Request $req){

        
        //Datos actuales del usuario loggeado
        $user = \Auth::user();
        $id = $user->id;

        
        /*Validar los campos*/
        $validate = $this->validate($req , [
            'name' => 'required|string|max:100',
            'surname' => 'required|string|max:200',
            //propiedad unica (solo permitiendo que sea igual al nick del usuario)
            'nick' => 'required|string|max:100|unique:users,nick,'.$id,
            //email
            'email' => 'required|email|max:255|unique:users,email,'.$id,
        ]);
        

        

        /*Recoger los datos del formulario*/
        $name = $req->input('name');
        $surname = $req->input('surname');
        $nick = $req->input('nick');
        $email = $req->input('email');



        //Asignar nuevos valores en la base de datos
        $user->name = $name;
        $user->surname = $surname;
        $user->nick = $nick;
        $user->email = $email;
        

        echo $nick;

        //Recibir imagen
        $image = $req->file('image');
        if($image){
            //Creamos un nombre para la imagen (en este caso tiempo + nombre de usuario)
            $image_path = time().$user->nick.".jpg";

            //Guardar el archivo en el servidor especificando el disco a guardar
            Storage::disk('users')->put($image_path , File::get($image) );

            //Guardar el dato del path en la base de datos
            $user->image = $image_path;
        }

        $user->update();

        //Retornar alguna ruta (utilizando el name de la ruta)
        return redirect()->route('config')
            /*Esto creara una session llamada message que 
            podremos detectarla con la vista */
            ->with(['message'=>'Usuario actualizado']);
    }
    /*=============================================================================*/

    /*=============================================================================*/
    //Metodo para mostrar el avatar
    public function getImage($filename){
        $file = Storage::disk('users')->get($filename);
        return new Response($file , 200);
    }
    /*=============================================================================*/

    

}
<file_sep>/app/Http/Controllers/ImageController.php
<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;

use Illuminate\Http\Request;
//Esta la necesitamos para enviar archivos a la vista
use Illuminate\Http\Response;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

//Modelo de Image
use App\Image;

class ImageController extends Controller
{
    public function __construct(){
        //Midleware de atuenticacion
        $this->middleware('auth');
    }

    public function create(){
        return view('image.create');
    }

    public function save(Request $req){

        //Datos del usuario loggeado
        $user = \Auth::user();
        $user_id = $user->id;

        

        $validate = $this->validate($req , [
            'description' => 'required',
            'image_path' => 'required|mimes:jpg,png,gif,jpeg'
        ]);

        //Obtenemos la imagen
        $image = $req->file('image_path');
        if($image){
            //Le damos un nombre a la imagen para que sea unico
            $image_path = time().$user->nick.'.jpg';
            $description = $req->input('description');
            //Guardar imagen
            Storage::disk('images')->put($image_path , File::get($image) );
            //Guardar el path del imagen al usuario
        }
        

        
        
        $image = DB::table('images')->insert(array(
            'user_id' => $user_id,
            'image_path' => $image_path,
            'description' => $description
        ));


        //Retornar alguna ruta (utilizando el name de la ruta)
        return redirect()->route('home')->with([
            'message' => 'La foto ha sido subida correctamente'
        ]);
    }

    /*============================================================================*/
    //Pintar las imagenes del muro
    public function print($filename){
        
        $file = Storage::disk('images')->get($filename);
        return new Response($file , 200);
    }


    //Controla una pagina donde se va a abrir una pagina completa para la imagen
    public function detail($id){

        $image = Image::find($id);

        return view ('image.detail' , [
            'image' => $image
        ]);
    }
    

}<file_sep>/app/Http/Controllers/HomeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
//Importar el modelo de imagenes
use App\Image;
  
class HomeController extends Controller{
    /**
     * Create a new controller instance.
     * @return void
     */
    public function __construct(){
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     * @return \Illuminate\Contracts\Support\Renderable
     */

     
    public function index(){
        //Obtenemos las imagenes de la db

        //Para una carga normal se utiliza el metodo get() 
        //pero como es paginacion usamos paginate(cantidad elem por paginas)
        $images = Image::orderBy('id' , 'desc')->paginate(2);
        
        //Retornamos a la vista enviando las imagenes
        return view('home' , [ 'images' => $images ]);
    }

}<file_sep>/app/Http/Controllers/CommentController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CommentController extends Controller{




    //Funcion para comentar
    public function create(Request $req){

        $current_date = date('Y-m-d H:i:s');

        //Obtener el id de la imagen a comentar
        $image_id = $req->input('image_id');
        //id del usuario loggeado
        $user_id = $req->input('user_id');
        //comentario
        $content = $req->input('content');

        //Validar comentario
        $validate = $this->validate($req , [
            'image_id' => 'required | integer',
            'content' => 'required | string | min:1 '
        ]);

        $save = DB::table('comments')->insert(array(
            'user_id' => $user_id,
            'image_id' => $image_id,
            'content' => $content,
            'created_at' => $current_date
        ));

        //Retornar alguna ruta (utilizando el name de la ruta)
        return redirect()->route('image.detail' , ['id' => $image_id])->with([
            'message' => 'Su comentario se añadio con exito.'
        ]);

    }

    public function delete($comment_id , $image_id){

        echo "comment_id: ".$comment_id."<br>";
        echo "image_id: ".$image_id."<br>";

        $delete = DB::table('comments')->where('id' , '=' , $comment_id )->delete();

        return redirect()->route('image.detail' , ['id' => $image_id])->with([
            'message' => 'Su comentario se borro con exito.'
        ]);
    }

}
<file_sep>/database/database.sql
CREATE DATABASE red_social;
USE red_social;

CREATE TABLE IF NOT EXISTS users(
    id INT(255) AUTO_INCREMENT NOT NULL,
    role VARCHAR(20),
    name VARCHAR(100),
    surname VARCHAR(200),
    nick VARCHAR(100),
    email VARCHAR(255),
    password VARCHAR(255),
    image VARCHAR(255),
    created_at DATETIME,
    updated_at DATETIME,
    remember_token VARCHAR(255),

    CONSTRAINT pk_users PRIMARY KEY (id)
)Engine=InnoDb;

CREATE TABLE IF NOT EXISTS images(
    id INT(255) AUTO_INCREMENT NOT NULL,
    user_id INT(255),
    image_path VARCHAR(255),
    description TEXT,
    created_at DATETIME,
    updated_at DATETIME,

    CONSTRAINT pk_images PRIMARY KEY (id),
    CONSTRAINT fk_images_users FOREIGN KEY (user_id) REFERENCES users(id)

)Engine=InnoDb;

CREATE TABLE IF NOT EXISTS comments(
    id INT(255) AUTO_INCREMENT NOT NULL,
    user_id INT(255),
    image_id INT(255),
    content TEXT,
    created_at DATETIME,
    updated_at DATETIME,

    CONSTRAINT pk_comments PRIMARY KEY (id),
    CONSTRAINT fk_comments_users FOREIGN KEY (user_id) REFERENCES users(id),
    CONSTRAINT fk_comments_images FOREIGN KEY (image_id) REFERENCES images(id)

)Engine=InnoDb;

CREATE TABLE IF NOT EXISTS likes(
    id INT(255) AUTO_INCREMENT NOT NULL,
    user_id INT(255),
    image_id INT(255),
    created_at DATETIME,
    updated_at DATETIME,

    CONSTRAINT pk_users PRIMARY KEY (id),
    CONSTRAINT fk_likes_users FOREIGN KEY (user_id) REFERENCES users(id),
    CONSTRAINT fk_likes_images FOREIGN KEY (image_id) REFERENCES images(id)

)Engine=InnoDb;


/*===============================================================================================
Users
==============================================================================================*/
INSERT INTO users VALUES(
    NULL, 
    'user' , 
    'Victor' , 
    'Robles' , 
    'victorroblesweb' , 
    '<EMAIL>' , 
    '12345678',
    null ,
    CURTIME() , 
    CURTIME()  ,
    NULL
);

INSERT INTO users VALUES(
    NULL, 
    'user' , 
    'Juan' , 
    'Lopez' , 
    'juanlopez' , 
    '<EMAIL>' , 
    '12345678',
    null ,
    CURTIME() , 
    CURTIME()  ,
    NULL
);

INSERT INTO users VALUES(
    NULL, 
    'user' , 
    'Manolo' , 
    'Garcia' , 
    'manologarcia' , 
    '<EMAIL>' , 
    '12345678',
    null ,
    CURTIME() , 
    CURTIME()  ,
    NULL
);

/*===============================================================================================
Images
==============================================================================================*/
INSERT INTO images VALUES(
    null,
    1,
    'test.jpg',
    'Descripcion de prueba 1',
    CURTIME(),
    CURTIME()
);
INSERT INTO images VALUES(
    null,
    1,
    'playa.jpg',
    'Descripcion de prueba 2',
    CURTIME(),
    CURTIME()
);
INSERT INTO images VALUES(
    null,
    1,
    'arena.jpg',
    'Descripcion de prueba 3',
    CURTIME(),
    CURTIME()
);
INSERT INTO images VALUES(
    null,
    3,
    'familia.jpg',
    'Descripcion de prueba 4',
    CURTIME(),
    CURTIME()
);



/*===============================================================================================
Comments
==============================================================================================*/
INSERT INTO comments VALUES(
    null,
    1,
    4,
    'Buena foto de familia',
    CURTIME(),
    CURTIME()
);
INSERT INTO comments VALUES(
    null,
    2,
    1,
    'Buena foto de playa',
    CURTIME(),
    CURTIME()
);
INSERT INTO comments VALUES(
    null,
    2,
    4,
    'Que bueno',
    CURTIME(),
    CURTIME()
);

/*===============================================================================================
Likes
==============================================================================================*/
INSERT INTO likes VALUES( NULL , 1, 4, CURTIME(), CURTIME() );
INSERT INTO likes VALUES( NULL , 2, 4, CURTIME(), CURTIME() );
INSERT INTO likes VALUES( NULL , 3, 1, CURTIME(), CURTIME() );
INSERT INTO likes VALUES( NULL , 3, 2, CURTIME(), CURTIME() );<file_sep>/routes/web.php
<?php

use App\Image;
//Importar controlladores
use App\Http\Controllers\UserController;
use App\Http\Controllers\ImageController;
use App\Http\Controllers\CommentController;

Route::get('/', 'HomeController@index')->name('home');

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
//Rutas para editar usuario
Route::get('/configuracion' , [UserController::class , 'config'])->name('config');
Route::post('/user/edit' , [UserController::class , 'update'])->name('user.update');
//Ruta para cargar el avatar
Route::get('/user/avatar/{filename}', [UserController::class , 'getImage'])->name('user.avatar');
//Ruta para administrar las imagenes
Route::get('/image/create' , [ImageController::class , 'create'])->name('image.create');
Route::post('/image/save' , [ImageController::class , 'save'])->name('image.save');

//Rutas para cargar las imagenes en el muro
Route::get('image/print/{filename}' , [ImageController::class , 'print'])->name('image.print');

//Ruta para abrir la pagina detallada de la imagen
Route::get('image/detail/{id}' , [ImageController::class , 'detail'])->name('image.detail');

//Ruta para comentar
Route::post('comment/create' , [CommentController::class , 'create'])->name('comment.create');
Route::get('comment/delete/{comment_id}/{image_id}' , [CommentController::class , 'delete'])->name('comment.delete');