laravel relationships

migration - posts


return new class extends Migration

{

    /**

     * Run the migrations.

     */

    public function up(): void

    {

        Schema::create('posts', function (Blueprint $table) {

            $table->id('postid')->unsignedBigInteger()->autoIncrement();

            $table->string('title');

            $table->text('description');

            $table->string('image');

            $table->unsignedBigInteger('user_id');

            $table->foreign('user_id')->references('id')->on('users');

            $table->timestamps();

        });

    }


    /**

     * Reverse the migrations.

     */

    public function down(): void

    {

        Schema::dropIfExists('posts');

    }


    public function users(): HasMany{

        $this->belongsTo(User::class);

    }

};

------------------------------------------------------------------------------------------------------------------------

 model - user

 public function posts(): HasMany{

        return $this->hasMany('users', 'user_id', 'id');

    }


model - posts

class Posts extends Model

{

    use HasFactory;

    protected $table = "posts";

    protected $primaryKey = "postid";


    public function users(): BelongsTo{

        return $this->belongsTo(User::class, 'user_id', 'id');

    } 

}    

---------------------------------------------------------------------


controller - 

 function home(Request $request){

        try{

            $post = Posts::all();

        return view('index',['post' => $post]);

        }catch(Exception $e){

            $post = null;

        }

    }


----------------------------------------------------------------------

blade - 

@foreach($post as $post)

<div class="row">

    <div class="col-1"></div>

    <div class="col-4">

        <img src="{{url('/storage', $post->image)}}" class="img-fluid" alt="...">

    </div>

    <div class="col-7">

    <b>{{$post->title}}</b>    

    <p class="fw-normal">

            {{ substr($post->description, 0, 100) }}{{ strlen($post->description) > 100 ? "..." : "" }}

        </p>

        <a href="{{url('/')}}/blog/{{$post->postid}}">read more</a>

        <br>

        Uploaded By, <b>{{$post->users->name}}</b>

        

    </div>

    <div class="col-1"></div>

</div>


<br>

<br>

@endforeach    

Popular posts from this blog

MCSL 216 MCA NEW Practical ~ common questions suggestions

dev chaeatsheet

STRAPI