samedi 3 octobre 2015

Laravel Eloquent retrive data from multiple tables

I have four tables

**Articles table**

 id
 title
 body
 owner_id
 category_id

**Favorite articles table**

  id
  user_id
  article_id

**User table**

 id
 user_name
 user_type

**Category table**

 id
 category_name

How to get list of favorite articles (article_name,owner_name,category_name) which related to currently logged user from db using laravel eloquent?

Is it possible to do it in single line request? e.g.:

$articles_data=Auth::user()->favorite_articles->article...



via Chebli Mohamed

Laravel 5.1 Redis cache

I'm trying to implement a very basic caching mechanism into my Laravel app.

I installed Redis, started it via terminal (src/redis-server) and changed cache from file to redis in Laravel's config file, but it takes LONGER than regular query when I use cache.

Am I missing something here?

Here's my FeedController.php

namespace App\Http\Controllers\Frontend\Feed;

use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Company;
use Redis;
use Cache;


class FeedController extends Controller
{

    public function index()
    {

        if (Cache::has('companies')) {
            $companies = Cache::get("companies");
        } else {
            $companies = Cache::remember("companies",10, function() {
                return Company::all();
            });

            Cache::put("companies", $companies, 10);
        }


        return view('index')->with('companies', $companies)
    }



via Chebli Mohamed

vendredi 2 octobre 2015

Laravel API Authentication

I am building an API using Laravel which will be used by both my Mobile and Web Applications. I am confused regarding authentication.

Basically the web application will be used by users both in logged in state and visitor state.

How would authentication work in that case? If the API uses username/password to authenticate a user what about visitors?

Also, how do I make sure its the webapp and mobile app thats making a request to the API? How do I ensure that someone doesn't programatically doesn't access the API and its only my apps that can request access to data?



via Chebli Mohamed

Appending "where" to model in foreach is not applying

I want to filter by multiple fields by appending ->where() to $usAddresses. My problem is that my view seems to be outputting $usAddresses::all(). I've tried applying ->get() outside of the loop to no avail. I've also tried $results = $usAddresses within the loop which does apply the "where" but only the latest.

        $usAddresses = new address_us;
        foreach ($request->all() as $fieldName => $value): 
            if (array_key_exists($fieldName, $usAddresses->first()->getAttributes())):
                echo "Searching for $fieldName where like %$value%<br>";
                $usAddresses->where($fieldName, "LIKE", "%{$value}%")->get();
            endif;
        endforeach;  
        return view('auth.app.merchkit.dashboard', ['usAddresses' => $usAddresses->paginate(15)])



via Chebli Mohamed

Laravel changing /home route after register

I implemented an email activation feature and I have some issues with it. If I open the activation link after I register ,localhost:8000/activate/tokenvariable, it redirects me to the /home url and gives an error. But if I delete cookies and visit it, account is being activated without a problem.

I couldn't understand what the problem is.

NotFoundHttpException in RouteCollection.php line 161:

Routes

// Authentication routes...
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');

// Registration routes...
Route::get('auth/register', 'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');

// Password reset link request routes...
Route::get('password/email', 'Auth\PasswordController@getEmail');
Route::post('password/email', 'Auth\PasswordController@postEmail');

// Password reset routes...
Route::get('password/reset/{token}', 'Auth\PasswordController@getReset');
Route::post('password/reset', 'Auth\PasswordController@postReset');

Route::get('activate/{token}', 'Auth\PasswordController@activate');

Route::get('/', function() {
return view('index');
});


Route::get('feed', 'Feed\FeedController@index');

FeedController

namespace App\Http\Controllers\Feed;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class FeedController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('feed');
    }
}

PasswordController

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Eloquent;
use Models;
use App\Models\User;
use Auth;
use Session;

class PasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Create a new password controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    public function activate($token) {
        //get token value.
        // find the user that belongs to that token.
        $activation = User::where("confirmation_code", $token)->get()->first();
        $activation->confirmed = 1;
        $activation->save();
        Auth::loginUsingId($activation->id, true);

    }
}

AuthController

namespace App\Http\Controllers\Auth;

use App\Models\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Mail;
use Auth;

class AuthController extends Controller
{

    protected $redirectTo = '/feed';
    protected $loginPath = '/';
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make(
          $data,
          [
            'name'     => 'required|max:255',
            'email'    => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
          ]
        );
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array $data
     * @return User
     */
    protected function create(array $data)
    {
        $confirmation_code = md5(uniqid(mt_rand(), true));
        $email = $data['email'];

        Mail::send('emails.verify', ['confirmation_code' => $confirmation_code], function ($m) use ($email) {
            $m->to($email)->subject("Here's your email");
        });

        return User::create(
          [
            'name'              => $data['name'],
            'email'             => $data['email'],
            'password'          => bcrypt($data['password']),
            'confirmation_code' => $confirmation_code,
          ]
        );
    }
}



via Chebli Mohamed

Laravel 5.1 session not saving

My session driver is memcached.

When I fire an event and broadcast event in redis, the flash messages are not saving, but If I don't fire an event it works just fine.

I'm on Laravel 5.1.

Please help me.



via Chebli Mohamed

Eloquent: firstorCreate() does not work with postgresSQL's JSON type

I am getting the following error:

Undefined function: 7 ERROR: operator does not exist: json = unknown

As 2 of my columns are of type JSON.

The code which throwing error is:

$this->firstOrCreate($records);



via Chebli Mohamed